A former Alabama state trooper shot a district attorney outside his office building on Thursday, prompting law enforcement officials to kill the gunman, the authorities said.

The prosecutor, Gregory Griggers, had returned from lunch and was sitting in his car in Demopolis, Ala., about 1 p.m. when he was attacked, the authorities said.

The former state trooper, identified as Steven Smith Jr., opened fire, shattering a car window and injuring Mr. Griggers in the face, said Michael W. Jackson, the district attorney in the state’s Fourth Judicial Circuit, which neighbors Mr. Griggers’s region.

Two law enforcement officers standing nearby then shot at Mr. Smith, killing him, Mr. Jackson said.

Mr. Griggers, the district attorney for Alabama’s 17th Judicial Circuit, was treated for minor injuries at a hospital and was released, Jason Roberts, a captain with the State Bureau of Investigation, said at a news conference streamed by a local news site.