Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中键盘中断user32.GetMessageW/user32.SetWinEventHook循环?_Python_Windows_Ctypes_Pywin32 - Fatal编程技术网

如何在python中键盘中断user32.GetMessageW/user32.SetWinEventHook循环?

如何在python中键盘中断user32.GetMessageW/user32.SetWinEventHook循环?,python,windows,ctypes,pywin32,Python,Windows,Ctypes,Pywin32,我似乎不知道如何让Ctrl-C中断这段代码。当您按下Ctrl-C键时,它会将键盘中断异常打印到控制台,但不会实际停止程序 我怎样才能让它真正停止 导入ctypes 导入ctypes.wintypes 从随机导入随机 user32=ctypes.windell.user32 ole32=ctypes.windell.ole32 事件\u MIN=0x00000001 事件_MAX=0x7FFFFFFF def_win_回调( hWinEventHook:int、事件、hwnd、idObject、i

我似乎不知道如何让Ctrl-C中断这段代码。当您按下Ctrl-C键时,它会将键盘中断异常打印到控制台,但不会实际停止程序

我怎样才能让它真正停止

导入ctypes
导入ctypes.wintypes
从随机导入随机
user32=ctypes.windell.user32
ole32=ctypes.windell.ole32
事件\u MIN=0x00000001
事件_MAX=0x7FFFFFFF
def_win_回调(
hWinEventHook:int、事件、hwnd、idObject、idChild、idEventThread、dwmsEventTime
):
如果random()>0.95:
打印(事件)
def loop():
ole32.CoInitializeEx(0)
win\u事件\u过程类型=ctypes.WINFUNCTYPE(
没有一个
ctypes.wintypes.HANDLE,
ctypes.wintypes.DWORD,
ctypes.wintypes.HWND,
ctypes.wintypes.LONG,
ctypes.wintypes.LONG,
ctypes.wintypes.DWORD,
ctypes.wintypes.DWORD,
)
win\u事件\u过程=win\u事件\u过程\u类型(\u win\u回调)
winevent_outofcontext=0x0000
user32.SetWinEventHook.restype=ctypes.wintypes.HANDLE
钩=无
hook=user32.SetWinEventHook(
事件最小值,事件最大值,0,赢事件过程,0,0,winevent\u上下文外,
)
断言钩子!=0
msg=ctypes.wintypes.msg()
打印(“启动消息循环”)
而user32.GetMessageW(ctypes.byref(msg),0,0,0)!=0:
打印(“msg”,msg)
user32.TranslateMessageW(msg)
user32.DispatchMessageW(消息)
如果名称=“\uuuuu main\uuuuuuuu”:
循环()

您是否尝试过尝试/例外?是的。我甚至把对
循环的调用包装在
try/except
中,但它不会捕获它。我可以在
\u win\u callback
函数中添加
try/except
,它会捕获错误,但无法在
循环中返回执行并退出
循环。您可以通过
CreateEventW
创建事件,并通过
fWaitAll=False
等待句柄,
dw毫秒=-1
(即
INFINITE
)和
dwWakeMask=0x4ff
(即
QS\u ALLINPUT
)。在循环之前重置事件,并通过设置事件在回调中处理
键盘中断
<如果设置了事件,则code>MsgWaitForMultipleObjects
将返回0(即
WAIT\u OBJECT\u 0
)。如果队列中有消息,则返回值为1,在这种情况下,调用
GetMessageW
。不要使用
windell
。它真的应该被弃用。使用
user32=ctypes.windl('user32',Use\u last\u error=True)
kernel32=ctypes.windl('kernel32',Use\u last\u error=True)
。如果函数记录为在失败时设置最后一个错误,请获取错误代码并通过
raise ctypes.WinError(ctypes.get\u last\u error())
引发异常。对于ole32.dll,大多数函数都返回一个
HRESULT
值,因此使用
ole32=ctypes.oledell('ole32')
,它会自动处理引发故障代码异常的问题。