The man, named as Claudio Giardiello, escaped on a scooter but was captured by police in Vimercate, a town some 25 kilometres (15 miles) outside Milan, the interior ministry said.
The dead were named by the Italian media as judge Fernando Ciampi and lawyer Lorenzo Alberto Claris Appiani, both shot on the third floor of the building after Giardiello managed to get a gun past security.
A third person was found dead inside the building after apparently suffering a heart attack, possibly brought on by the shooting, emergency services said.
Valerio Maraniello, who once acted as a lawyer for the shooter, told AFP his ex-client was "an aggressive person, a little paranoid."
More From This Section
"He was always convinced people were trying to cheat him. He never listened to advice," he said, adding that he was "not completely surprised" by the deadly attack.
Regional authorities were shocked that anyone had managed to get into the court building with a gun.
"It's disturbing that just anyone can get into the Palace of Justice armed," said the head of the Lombardy region, Roberto Maroni.
Interior Minister Angelino Alfano, who was in Milan for a national committee meeting on public order and safety ahead of the 2015 Milan expo which opens in May, was called on to investigate security at the court.
The sound of shots sparked panic, with lawyers bolting for the exit while police officers went floor to floor searching for the gunman, who was initially thought to be still inside the building.
"All of a sudden we heard at least three or four shots," lawyer Marcello Ilia told AFP outside the court.