python模擬鍵盤輸入 切換鍵盤布局

2022-08-20 09:51:10 字數 2188 閱讀 9476

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):

if win32api.loadkeyboardlayout('0x0409', win32con.klf_activate) == none:

return exception('載入鍵盤失敗')

# 語言**

# lid =

# 獲取前景視窗控制代碼

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('還原鍵盤成功!')

microsoft鍵盤碼參考

這位兄弟寫的關於模擬鍵盤非常全

Python模擬鍵盤輸入

2.程式實現 import win32api import win32con win32api.keybd event 17,0,0,0 ctrl鍵位碼是17 win32api.keybd event 86,0,0,0 v鍵位碼是86 win32api.keybd event 86,0,win32c...

python 模擬鍵盤輸入

備忘錄 import win32api import win32con win32api.keybd event 17,0,0,0 ctrl鍵位碼是17 win32api.keybd event 86,0,0,0 v鍵位碼是86 win32api.keybd event 86,0,win32con....

用Python模擬鍵盤輸入

pywin安裝模組 import win32api import win32con win32api.keybd event 17,0,0,0 ctrl鍵位碼是17 win32api.keybd event 86,0,0,0 v鍵位碼是86 win32api.keybd event 86,0,win...