Accurate gain control of PET detectors is a prerequisite for quantitative accuracy. A shift in the 511 keV peak position can lead to errors in scatter correction, degrading quantitation. The PET detectors in a PET/MR scanner are subject to thermal transients due to eddy currents induced during gradient-intensive MRI sequences. Since the gain of silicon photomultiplier-based detectors changes with temperature, good gain control is particularly challenging. In this paper we describe a method that utilizes information from the entire singles spectrum to create a real-time gain control method that maintains gain of PET detectors stable within approximately ±0.5% (±2.5 keV) with varying levels of scatter and in the presence of significant thermal transients. We describe the methods used to combine information about multiple peaks and how this algorithm is implemented in a way that permits real-time processing on a field-programmable gate array. Simulations demonstrate rapid response time and stability. A method ('virtual scatter filter') is also described that extracts unscattered photopeak events from phantom data and demonstrates the accuracy of the photopeak for various radionuclides that emit energies in addition to the pure 511 keV annihilation peak. Radionuclides 52 Mn, 55 Co, 64 Cu, 89 Zr, 90 Y, and 124 I are included in the study for their various forms of spectral contamination.