Created
July 12, 2012 10:07
-
-
Save romichi/3097160 to your computer and use it in GitHub Desktop.
pythonからsendInputを使う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding:utf-8 -*- | |
import time | |
from ctypes import * | |
import win32gui, win32con | |
PUL = POINTER(c_ulong) | |
class KeyBdInput(Structure): | |
_fields_ = [("wVk", c_ushort), #virtual-key code | |
("wScan", c_ushort), #hardware scan code | |
("dwFlags", c_ulong), #keystroke | |
("time", c_ulong), #time stamp | |
("dwExtraInfo", PUL)] | |
class MouseInput(Structure): | |
_fields_ = [("dx", c_long), | |
("dy", c_long), | |
("mouseData", c_ulong), | |
("dwFlags", c_ulong), | |
("time",c_ulong), | |
("dwExtraInfo", PUL)] | |
class HardwareInput(Structure): | |
_fields_ = [("uMsg", c_ulong), | |
("wParamL", c_short), | |
("wParamH", c_ushort)] | |
class Input_I(Union): | |
_fields_ = [("mi", MouseInput), | |
("ki", KeyBdInput), | |
("hi", HardwareInput)] | |
class Input(Structure): | |
_fields_ = [("type", c_ulong), | |
("ii", Input_I)] | |
class SendKey(object): | |
def __init__(self): | |
self.EXTENDED_KEYS = [win32con.VK_LEFT, win32con.VK_DOWN, win32con.VK_UP, win32con.VK_RIGHT] | |
def generateVirtualKey(self, key): | |
keyMap = { | |
"left": win32con.VK_LEFT, | |
"down": win32con.VK_DOWN, | |
"up": win32con.VK_UP, | |
"right": win32con.VK_RIGHT, | |
} | |
if key in keyMap: | |
return keyMap[key] | |
else: | |
return ord(key.upper()) | |
def sendKey(self, key, keyStroke): | |
virtualKey = self.generateVirtualKey(key) | |
scanCode = windll.user32.MapVirtualKeyA(virtualKey, 0) | |
dwFlags = win32con.KEYEVENTF_EXTENDEDKEY if virtualKey in self.EXTENDED_KEYS else 0 | |
if keyStroke == 'down': | |
pass | |
elif keyStroke == 'up': | |
dwFlags = dwFlags | win32con.KEYEVENTF_KEYUP | |
else: | |
print u'keyStroke Error' | |
dwExtraInfo = c_ulong(0) | |
ii_ = Input_I() | |
ii_.ki = KeyBdInput(virtualKey, scanCode, dwFlags, 0, pointer(dwExtraInfo)) | |
#keyの送信 | |
nInputs = 1 | |
pInputs = Input(win32con.INPUT_KEYBOARD, ii_) | |
windll.user32.SendInput(nInputs, pointer(pInputs), sizeof(pInputs)) | |
if __name__ == '__main__': | |
sk = SendKey() | |
sk.sendKey('Z', 'down') | |
time.sleep(0.1) | |
sk.sendKey('Z', 'up') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment