Python Ctypes键盘事件

时间:2017-05-01 18:42:51

标签: python winapi keyboard ctypes pywin32

我有一些python(2.7.13)代码如下:

import win32api, win32con, ctypes

ctypes.windll.user32.keybd_event(0xA5, 0, 0, 0) # Right Menu Key
ctypes.windll.user32.keybd_event(0x73, 0, 0, 0) # F4

ctypes.windll.user32.keybd_event(0x0D, 0, 0, 0) #Enter Key

每当我运行代码时,我的计算机都会出错,即使在我关闭Python之后也是如此。似乎总是按下 alt 键。如果我手动按 alt 键,则会停止。

另一件事是这段代码意味着关闭shell。它只适用于正确的菜单键代码,而不是alt键代码和左菜单键代码。 (我知道有其他方法可以关闭shell,但这会关闭任何东西。)

以下是我想知道的事情:

  1. 为什么这会按住 alt 键?
  2. 如何在我的代码中停止此操作?
  3. 为什么这不适用于alt键代码或左键菜单代码?
  4. 提前感谢任何帮助过的人。

2 个答案:

答案 0 :(得分:1)

我不知道你是否还在寻找答案,但我认为问题在于你没有模拟关键命令。添加以下三行代码应该能够模拟您要查找的内容。

对于下面的代码,我假设你想要它顺序(即按右菜单键,按F4键,然后按回车键)。但是,如果您想要按住它,就像Shift +' a'一样,您可以同时调用两个按键事件,然后同时调用两个按键事件。

import win32api, win32con, ctypes
ctypes.windll.user32.keybd_event(0xA5, 0, 0, 0) # Right Menu Key Down
ctypes.windll.user32.keybd_event(0xA5, 0, 0x0002, 0) # Right Menu Key Up
ctypes.windll.user32.keybd_event(0x73, 0, 0, 0) # F4 Down
ctypes.windll.user32.keybd_event(0x73, 0, 0x0002, 0) # F4 Up
ctypes.windll.user32.keybd_event(0x0D, 0, 0, 0) #Enter Key Down
ctypes.windll.user32.keybd_event(0x0D, 0, 0x0002, 0) #Enter Key Up

答案 1 :(得分:0)

您可以使用pywinauto模拟用户输入。你的问题已经解决了。可以使用子模块pywinauto.keyboard

from pywinauto.keyboard import SendKeys
SendKeys('%{F4}{PAUSE 0.2}{ENTER}') # press Alt+F4, pause, press Enter

只需在命令行中运行pip install pywinauto