python模拟键盘输入+切换键盘布局
Posted jokerbi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python模拟键盘输入+切换键盘布局相关的知识,希望对你有一定的参考价值。
PostMessage()
def keyHwnd(hwndEx, char):
"""
向指定控件输入值
:param hwndEx: 控件句柄
:param char: 字符串
:return: True or Flase
"""
try:
for _ in char:
print('key:%s ascii:%d' % (_, ord(_)))
win32api.PostMessage(hwndEx, win32con.WM_CHAR, ord(_), 0)
time.sleep(random.uniform(0,0.2))
except Exception as e:
print(e)
return False
return True
hwnd = win32gui.FindWindow(None,'a.txt - 记事本')
print(hwnd)
win32gui.SetForegroundWindow(hwnd)
hwndex = win32gui.FindWindowEx(hwnd,None,'Edit', None)
keyHwnd(hwndex,'撒地方SDFkof;ldsojfdfdsjfd;slkjfdlksjfkldsjflkdsjlkfjkldsljkfjdssj')
切换键盘布局
该功能封装成了一个装饰器,函数执行完恢复了原键盘布局
import win32con
from win32con import WM_INPUTLANGCHANGEREQUEST
import win32gui
import win32api
def setKeyboardLayout_en(inner):
def wrapper(*args, **kwargs):
if win32api.LoadKeyboardLayout('0x0409', win32con.KLF_ACTIVATE) == None:
return Exception('加载键盘失败')
# 语言代码
# https://msdn.microsoft.com/en-us/library/cc233982.aspx
LID = 0x0804: "Chinese (Simplified) (People's Republic of China)",
0x0409: 'English (United States)'
# 获取前景窗口句柄
hwnd = win32gui.GetForegroundWindow()
# 获取前景窗口标题
title = win32gui.GetWindowText(hwnd)
# 获取键盘布局列表
im_list = win32api.GetKeyboardLayoutList()
im_list = list(map(hex, im_list))
print(im_list)
oldKey = hex(win32api.GetKeyboardLayout())
# 设置键盘布局为英文
result = win32api.SendMessage(
hwnd,
WM_INPUTLANGCHANGEREQUEST,
0,
0x4090409)
if result == 0:
print('设置英文键盘成功!')
inner(*args,*kwargs)
result = win32api.SendMessage(
hwnd,
WM_INPUTLANGCHANGEREQUEST,
0,
oldKey)
if result == 0:
print('还原键盘成功!')
return wrapper
ascii标准码
keybd_event()
win32api.keybd_event(65, 0, 0, 0)
time.sleep(random.uniform(0, 0.5))
win32api.keybd_event(65, 0, win32con.KEYEVENTF_KEYUP, 0)
以上是关于python模拟键盘输入+切换键盘布局的主要内容,如果未能解决你的问题,请参考以下文章
selenium webdriver从安装到使用(python语言),显示等待和隐性等待用法,切换窗口或者frame,弹框处理,下拉菜单处理,模拟鼠标键盘操作等