PythonでDirectInputのキーボード入力が行いたいです。
https://pythonprogramming.net/direct-input-game-python-plays-gta-v/
↑のサイトを参考に実行してみたのですが、エラーが出て、解決法が分かりません。
Python
1#directKeys.py 2import ctypes 3import time 4 5SendInput = ctypes.windll.user32.SendInput 6 7 8W = 0x11 9A = 0x1E 10S = 0x1F 11D = 0x20 12 13# C struct redefinitions 14PUL = ctypes.POINTER(ctypes.c_ulong) 15class KeyBdInput(ctypes.Structure): 16 _fields_ = [("wVk", ctypes.c_ushort), 17 ("wScan", ctypes.c_ushort), 18 ("dwFlags", ctypes.c_ulong), 19 ("time", ctypes.c_ulong), 20 ("dwExtraInfo", PUL)] 21 22class HardwareInput(ctypes.Structure): 23 _fields_ = [("uMsg", ctypes.c_ulong), 24 ("wParamL", ctypes.c_short), 25 ("wParamH", ctypes.c_ushort)] 26 27class MouseInput(ctypes.Structure): 28 _fields_ = [("dx", ctypes.c_long), 29 ("dy", ctypes.c_long), 30 ("mouseData", ctypes.c_ulong), 31 ("dwFlags", ctypes.c_ulong), 32 ("time",ctypes.c_ulong), 33 ("dwExtraInfo", PUL)] 34 35class Input_I(ctypes.Union): 36 _fields_ = [("ki", KeyBdInput), 37 ("mi", MouseInput), 38 ("hi", HardwareInput)] 39 40class Input(ctypes.Structure): 41 _fields_ = [("type", ctypes.c_ulong), 42 ("ii", Input_I)] 43 44# Actuals Functions 45 46def PressKey(hexKeyCode): 47 extra = ctypes.c_ulong(0) 48 ii_ = Input_I() 49 ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) ) 50 x = Input( ctypes.c_ulong(1), ii_ ) 51 ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x)) 52 53def ReleaseKey(hexKeyCode): 54 extra = ctypes.c_ulong(0) 55 ii_ = Input_I() 56 ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) ) 57 x = Input( ctypes.c_ulong(1), ii_ ) 58 ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x)) 59 60if __name__ == '__main__': 61 PressKey(0x11) 62 time.sleep(1) 63 ReleaseKey(0x11) 64 time.sleep(1)
を作り、実際に入力を行うtest.pyを同じディレクトリに作りました。
python
1# -*- coding: utf-8 -*- 2#test.py 3import numpy as np 4from PIL import ImageGrab 5import cv2 6import time 7import pyautogui 8from directkeys import PressKey, W, A, S, D 9 10def process_img(image): 11 original_image = image 12 # convert to gray 13 processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 14 # edge detection 15 processed_img = cv2.Canny(processed_img, threshold1 = 200, threshold2=300) 16 return processed_img 17 18def main(): 19 20 for i in list(range(4))[::-1]: 21 print(i+1) 22 time.sleep(1) 23 24 last_time = time.time() 25 while True: 26 PressKey(W) 27 screen = np.array(ImageGrab.grab(bbox=(0,40,800,640))) 28 #print('Frame took {} seconds'.format(time.time()-last_time)) 29 last_time = time.time() 30 new_screen = process_img(screen) 31 cv2.imshow('window', new_screen) 32 #cv2.imshow('window',cv2.cvtColor(screen, cv2.COLOR_BGR2RGB)) 33 if cv2.waitKey(25) & 0xFF == ord('q'): 34 cv2.destroyAllWindows() 35 break 36 37main() 38
しかし、実行したところ
PressKey(W)の行でエラーが出力されました。
↓↓エラーは以下の通りです。↓↓
ArgumentError: argument 2: <class 'TypeError'>: expected LP_INPUT instance instead of LP_Input
解決法をご教授ください。
よろしくお願いします。
あなたの回答
tips
プレビュー