Key guns were apparently used in the 17th and 18th century, but they are pretty rare. They were apparently intended to be used by jailers for self-defense purposes, when they were making their daily inspections of the prison cells. The idea being that the jailer could use the same object to open the cell door and also defend himself, in case the prisoner inside tried to escape.
Key guns were initially incredibly primitive devices. The example above is merely a tube sealed on one end, with a touch-hole on top. Note the lack of any firing mechanism. The jailer would have carried a lit cigarette or cigar in his mouth. To discharge this weapon, the jailer would touch his cigar on the touch-hole and light the powder within the key.
Some other examples had actual firing mechanisms. For instance, we have a model that uses a matchlock firing mechanism, one using a flintlock and another one using percussion cap technology.
Click on images to enlarge.
Whether these weapons were actually practical or not is a completely different matter. These are all small-caliber and short range firearms with low stopping-power and it isn't quite clear how usable one of these is once the jailer has started turning the key, because the gun can no longer point at the prisoner and the jailer can't put his finger on the trigger while turning the key. No wonder then that these weren't very popular.