Python按键模拟会干扰按键

时间:2018-11-27 22:21:19

标签: python keypress

当我尝试编写一个在Minecraft上自动行走,运行和移动的程序时,我遇到了这个问题,问题是当我尝试使其运行或移动时,它会干扰Windows按键。我该如何预防?

代码如下:

import os
import win32gui as win
from time import sleep
from directkeys import PressKey, ReleaseKey, KEYS

print("Modes: WALK, RUN, SHIFT")

mode = input("Select AutoKey Mode> ")
print(f"Selected mode: {mode}")
if mode == "RUN":
    print("RUN mode has some issues that could make your start menu open when you pause/unpause MC, and other keystrokes may not work")

while True:
    title = win.GetWindowText(win.GetForegroundWindow())
    #print(title)

    if "Minecraft " in title:
        if mode == "WALK":
            PressKey(KEYS.W)
        elif mode == "RUN":
            PressKey(KEYS.W)
            PressKey(KEYS.LCTRL)
        elif mode == "SHIFT":
            PressKey(KEYS.SHIFT)
    else:
        ReleaseKey(KEYS.W)
        ReleaseKey(KEYS.LCTRL)
        ReleaseKey(KEYS.SHIFT)
    sleep(0.10)

这是DirectKeys模块的代码:

import ctypes
import time

class KEYS:
    W = 0x11
    A = 0x1E
    S = 0x1F
    D = 0x20
    LCTRL = 0x1D
    SHIFT = 0x2A

SendInput = ctypes.windll.user32.SendInput

# C struct redefinitions 
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
    _fields_ = [("wVk", ctypes.c_ushort),
                ("wScan", ctypes.c_ushort),
                ("dwFlags", ctypes.c_ulong),
                ("time", ctypes.c_ulong),
                ("dwExtraInfo", PUL)]

class HardwareInput(ctypes.Structure):
    _fields_ = [("uMsg", ctypes.c_ulong),
                ("wParamL", ctypes.c_short),
                ("wParamH", ctypes.c_ushort)]

class MouseInput(ctypes.Structure):
    _fields_ = [("dx", ctypes.c_long),
                ("dy", ctypes.c_long),
                ("mouseData", ctypes.c_ulong),
                ("dwFlags", ctypes.c_ulong),
                ("time",ctypes.c_ulong),
                ("dwExtraInfo", PUL)]

class Input_I(ctypes.Union):
    _fields_ = [("ki", KeyBdInput),
                 ("mi", MouseInput),
                 ("hi", HardwareInput)]

class Input(ctypes.Structure):
    _fields_ = [("type", ctypes.c_ulong),
                ("ii", Input_I)]

# Actuals Functions

def PressKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

# directx scan codes http://www.gamespp.com/directx/directInputKeyboardScanCodes.html

if __name__ == '__main__':
    while (True):
        PressKey(0x11)
        time.sleep(1)
        ReleaseKey(0x11)
        time.sleep(1)

有人可以帮我吗,我真的不知道该怎么解决!

0 个答案:

没有答案