如何在Python中生成键盘事件? [英] How to generate keyboard events in Python?

查看:164
本文介绍了如何在Python中生成键盘事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短摘要:

我正在尝试创建一个程序,该程序会将键盘事件发送到计算机,出于所有目的,应将模拟事件视为键盘上的实际击键.

I am trying to create a program that will send keyboard events to the computer that for all purposes the simulated events should be treated as actual keystrokes on the keyboard.

原始帖子:

我正在寻找一种使用python生成键盘事件的方法.

I am looking for a way to generate keyboard events using python.

假设该函数收到一个必须模拟按下的键,如下所示:

Assume that the function receives a key that it must simulate pressing, like so:

keyboardevent('a') #lower case 'a'
keyboardevent('B') #upper case 'B'
keyboardevent('->') # right arrow key

def keyboardevent(key):
    #code that simulated 'key' being pressed on keyboard

以上显然是示例,但是我正在寻找的是可以用来模拟键盘事件的库,模块或其他任何东西.

The above are obviously examples, but what I am looking for is a library, module, or whatever, which I can use to simulate keyboard events.

note :这不同于将字符发送到记事本,或在字段等中输入文本.我希望python脚本模拟实际的键盘事件,计算机会认为确实存在键盘事件.

note: This is different than sending characters to notepads, or inputting text into fields or such. I want the python script to simulate an actual keyboard event, the computer will think that there is really a keyboard event.

特别注意:

我不想将击键发送到活动窗口-我希望系统相信键盘的按键被按下,这是细微的差别,因为某些活动窗口不接受某些键组合,或者如果我想通过我的脚本为后台进程使用键盘快捷键,它们不需要通过活动窗口

I don't want to send keystrokes to the active window - I want the system to believe the keyboard's keys are being pressed, subtle difference, as some active-windows do not accept certain key-combinations, or if I wanted to use keyboard shortcuts for background processes through my script, they don't need to go through the active-window

到目前为止,我已经看过这些东西:

So far I have looked at these things:

为最前端的应用程序生成键盘事件

如何通过Python生成键盘按键事件?

那些都是关于苹果的,根本没有帮助.

Which were all about apple and didn't help at all.

这:

哪种方法最简单在Python上模拟键盘和鼠标?

似乎可能正是我所需要的,但是我找不到该库或任何文档.

Which seems like it might be what I need, but I can not find the library for it or any documentation.

我也搜索了更多地方,但是还没有找到解决方法.

I have searched more places as well, but have yet to find a solution.

推荐答案

可以使用ctypes完成:

It can be done using ctypes:

import ctypes
from ctypes import wintypes
import time

user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

# msdn.microsoft.com/en-us/library/dd375731
VK_TAB  = 0x09
VK_MENU = 0x12

# C struct definitions

wintypes.ULONG_PTR = wintypes.WPARAM

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

    def __init__(self, *args, **kwds):
        super(KEYBDINPUT, self).__init__(*args, **kwds)
        # some programs use the scan code even if KEYEVENTF_SCANCODE
        # isn't set in dwFflags, so attempt to map the correct code.
        if not self.dwFlags & KEYEVENTF_UNICODE:
            self.wScan = user32.MapVirtualKeyExW(self.wVk,
                                                 MAPVK_VK_TO_VSC, 0)

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

# Functions

def PressKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode,
                            dwFlags=KEYEVENTF_KEYUP))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def AltTab():
    """Press Alt+Tab and hold Alt key for 2 seconds
    in order to see the overlay.
    """
    PressKey(VK_MENU)   # Alt
    PressKey(VK_TAB)    # Tab
    ReleaseKey(VK_TAB)  # Tab~
    time.sleep(2)
    ReleaseKey(VK_MENU) # Alt~

if __name__ == "__main__":
    AltTab()

hexKeyCode是Windows API定义的虚拟键盘映射.代码列表在MSDN上可用:虚拟键代码(Windows)

hexKeyCode is the virtual keyboard mapping as defined by the Windows API. The list of codes is available on MSDN: Virtual-Key Codes (Windows)

这篇关于如何在Python中生成键盘事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆