A man walked into a municipal building south of Pittsburgh on Wednesday and shot four people — including a police sergeant — before a police officer fatally shot him outside a courtroom where the gunman was to appear for a hearing in a domestic violence case, the authorities said.

Around 2 p.m., the gunman walked into the lobby of the Masontown Borough Municipal Center and began shooting a handgun, said Richard Bower, the district attorney of Fayette County. A police sergeant “engaged” the gunman and was shot, Mr. Bower said. The gunman then shot two men and one woman, Mr. Bower said.

A police officer then entered the lobby and shot the gunman multiple times, killing him, Mr. Bower said.

An official later identified the gunman as Patrick S. Dowdell, 61, of Masontown, Pa.

All four shooting victims were taken to hospitals with what Lt. Steven C. Dowlin of the Pennsylvania State Police said were nonlife-threatening injuries. Specifically, the police sergeant was said to be in good condition. Three others — a 47-year-old man, a 35-year-old man and a 39-year-old woman — were treated at a hospital in Morgantown, W.Va., and released.