A man arrested for trespassing at O'Hare International Airport grabbed a gun away from a police officer Friday and shot himself to death in a crowded courtroom, authorities said.

Carlos Astacio, 46, an immigrant from the Dominican Republic who listed his residence as Pompano Beach, Fla., had apparently been sitting in Misdemeanor Court for much of the morning before the 1:15 p.m. shooting, police Sgt. Rocco Rinaldi said.More than 20 other people were in the courtroom, including Associate Judge Stewart D. Spitzer, who was seated at the bench, but none was injured.

Astacio was charged with criminal trespassing early Friday morning after riding a conveyor belt used to move baggage onto the tarmac at the world's busiest airport. Police suspect Astacio was trying to sneak aboard a Mexicana Airlines flight to Mexico City.

After being processed at a police station, Astacio was brought to the adjoining courtroom at 9:30 a.m. for a preliminary hearing, Rinaldi said. The case was later called and Astacio was freed on his own recognizance and given an Oct. 11 court date.

But he apparently remained seated in the gallery of the courtroom and watched the proceedings for several hours. When a group of defendants was called before Spitzer, Astacio walked up with them and grabbed a .32-caliber revolver from the holster of Patrolman Raymond Worthem, who is assigned to the courtroom and was doing some paperwork at a desk a few feet away from the judge.

As the judge ducked beneath the bench and spectators ran from the courtroom, Astacio waved the gun in the air and yelled, "Somebody's trying to get me," Chief Deputy Sheriff Neil C. Sullivan said.

Police tried to talk Astacio into handing over the weapon, but he fired a shot in the direction of two officers that went into the ceiling above them.

"At this point, Astacio put the gun to his head and shot himself," Sullivan said.