Police said the boy was in an office with a teacher and another student at South Orangetown Middle School when he pulled a pellet gun that resembled a police-issued automatic sidearm from his backpack and wordlessly pointed it at the teacher.
Then he ran outside and pointed it at motorists.
A retired NYPD officer saw what was happening and approached the 14-year-old.
"He backed his car up, he got out of his car, he was able to subdue the student and take the handgun away from him," Orangetown Police Chief Kevin Nulty said.
The name of the retired officer was not made public.
The boy was charged with menacing, weapon possession and four counts of attempted robbery, the chief said. The robbery charges allege attempted carjacking.
"We are under the belief he was attempting to get access to one of those cars," Nulty said.
The gun was loaded with soft pellets. They usually don't hurt people if they're fired from a distance, authorities said.
The school went into lockdown at around 9 a.m. while police investigated. The 880-student school remained in lockdown until 11:30 a.m.
The school houses offices for the school district and is the same location where an angry parent held Ken Mitchell, the superintendent, hostage at gunpoint last June 9. In that incident, Mitchell was able to wrestle away the weapon without anyone getting hurt.
The incident on Tuesday "did certainly bring back a very unpleasant memory," said Mitchell.