Easy - build a mechanical lock into the gun. Many guns have a safety lever that you must turn before you can shoot. The "safety" will now be a key that you insert & turn - then your gun is useable. A lock can be made as sturdy as the rest of the gun, so it won't fail you.
Locks can be picked, but a villain that successfully grabs your gun won't have time for that before you hit him with something.
Smith & Wesson and other manufacturers has been building revolvers with these locks since the 70's. Nobody I know actually uses the locks, nor do I.
Use of a firearm is a last resort - when a villain comes running at you with a knife, your sidearm needs to be ready to shoot right fucking now.
Are you going to have time to fumble for a key and unlock your weapon in the 2 seconds it takes him to cover the distance between you?