A school shooting may have been narrowly averted on Wednesday — thanks in part to the quick response of a school resource officer, who shot a gunman before anyone else was harmed.

The authorities in Dixon, Ill., said the officer, Mark Dallas, was on duty at Dixon High School near a gymnasium, where students were gathered for a graduation rehearsal, when he heard gunshots at 8:06 a.m. He confronted the gunman, chased him out of the school and pursued him down a nearby street, the police said.

The gunman, a student at the school identified as Matthew A. Milby, 19, of Dixon, shot at the officer but missed, the police said. Mr. Dallas returned fire and struck Mr. Milby, who was taken to a hospital for non-life-threatening injuries.

“I could not be more proud of the police officer and the way he responded in this situation,” Dixon Police Chief Steve Howell said. “Because of his heroic actions, countless lives were saved. We are forever indebted to him for his service and his bravery.”