import time
import win32api
import win32con
import win32gui
class VirtualKeyboard:
def __init__(self, hwnd):
self.hwnd = hwnd
self.hwnd_title = win32gui.GetWindowText(hwnd)
def key_press(self, key: str, interval=0.1):
key = ord(key.upper())
win32api.PostMessage(self.hwnd, win32con.WM_KEYDOWN, key, 0)
time.sleep(interval)
win32api.PostMessage(self.hwnd, win32con.WM_KEYUP, key, 0)
def key_down(self, key: str):
key = ord(key.upper())
win32api.PostMessage(self.hwnd, win32con.WM_KEYDOWN, key, 0)
def key_up(self, key: str):
key = ord(key.upper())
win32api.PostMessage(self.hwnd, win32con.WM_KEYUP, key, 0)
def mouse_move(self, x, y):
x = int(x)
y = int(y)
point = win32api.MAKELONG(x, y)
win32api.PostMessage(self.hwnd, win32con.WM_MOUSEMOVE, None, point)
def mouse_up(self, x, y, button="L"):
x = int(x)
y = int(y)
button = button.upper()
point = win32api.MAKELONG(x, y)
if button == "L":
win32api.PostMessage(self.hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, point)
elif button == "R":
win32api.PostMessage(self.hwnd, win32con.WM_RBUTTONUP, win32con.MK_RBUTTON, point)
def mouse_down(self, x, y, button="L"):
x = int(x)
y = int(y)
button = button.lower()
point = win32api.MAKELONG(x, y)
if button == "L":
win32api.PostMessage(self.hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, point)
elif button == "R":
win32api.PostMessage(self.hwnd, win32con.WM_RBUTTONDOWN, win32con.MK_RBUTTON, point)
def mouse_double(self, x, y):
x = int(x)
y = int(y)
point = win32api.MAKELONG(x, y)
win32api.PostMessage(self.hwnd, win32con.WM_LBUTTONDBLCLK, win32con.MK_LBUTTON, point)
win32api.PostMessage(self.hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, point)
def mouse_move_press(self, x, y):
x = int(x)
y = int(y)
point = win32api.MAKELONG(x, y)
win32api.PostMessage(self.hwnd, win32con.WM_MOUSEMOVE, None, point)
win32api.PostMessage(self.hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, point)
win32api.PostMessage(self.hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, point)
def mouse_move_press_double(self, x, y):
x = int(x)
y = int(y)
point = win32api.MAKELONG(x, y)
win32api.PostMessage(self.hwnd, win32con.WM_MOUSEMOVE, None, point)
win32api.PostMessage(self.hwnd, win32con.WM_LBUTTONDBLCLK, win32con.MK_LBUTTON, point)
win32api.PostMessage(self.hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, point)
if __name__ == '__main__':
try:
handle = win32gui.FindWindow("Notepad", None)
print("窗口句柄是:{}".format(handle))
vkb = VirtualKeyboard(67626)
vkb.mouse_move_press(50, 50)
vkb.key_press("A")
except Exception as e:
print("窗口句柄获取失败:{}".format(e))