⌨️
Pythonで全てのキーボード入力を無効化 (keyboardライブラリ)
まえがき
検索しても出てこなかったので、地道にひとつずつキーを押して調べました。
入力されたキー名はkeyboard.read_key()でわかります。
環境
・Windows10 64bit
・Python 3.7.5
・keyboard 0.13.5
コード
import keyboard
import time
AllKeySet = {
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'!','"','#','$','%','&',"'",'(',')','=','~','|','-','^','\\','@','[',';',':',']',',','`','{','}','<','>','?','_',
'0','1','2','3','4','5','6','7','8','9','.','+','*','/',"num lock",
"esc","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12","print screen","scroll lock","pause","sys req",
"insert","delete","home","end","page up","page down",
"right","down","left","up",
"半角/全角","tab","caps lock","shift","ctrl","left windows","alt","無変換","space",
"変換","ひらがな","right alt","right windows","menu","right ctrl","right shift","enter","backspace"
}
# すべてのキー入力を無効化
for key in AllKeySet:
keyboard.block_key(key)
time.sleep(5) # 5秒間待つ
# キー入力を無効化を解除
keyboard.unhook_all()
おまけ (WindowsAPIからのキー入力はできちゃう)
import keyboard
import time
import win32com.client # WindowsAPIからのキー入力テスト用
# WindowsAPIからのキー入力テスト用
shell = win32com.client.Dispatch("WScript.Shell")
AllKeySet = {
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'!','"','#','$','%','&',"'",'(',')','=','~','|','-','^','\\','@','[',';',':',']',',','`','{','}','<','>','?','_',
'0','1','2','3','4','5','6','7','8','9','.','+','*','/',"num lock",
"esc","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12","print screen","scroll lock","pause","sys req",
"insert","delete","home","end","page up","page down",
"right","down","left","up",
"半角/全角","tab","caps lock","shift","ctrl","left windows","alt","無変換","space",
"変換","ひらがな","right alt","right windows","menu","right ctrl","right shift","enter","backspace"
}
# すべてのキー入力を無効化
for key in AllKeySet:
keyboard.block_key(key)
time.sleep(2) # 2秒間待つ
shell.SendKeys("a") # WindowsAPIからのキー入力はできちゃう
time.sleep(2) # 2秒間待つ
# キー入力を無効化を解除
keyboard.unhook_all()
keyboardライブラリ
Discussion