使用python将一些键发送到非活动窗口

kil*_*dio 10 python windows key send sendkeys

我正在尝试使用python将一些密钥发送到非活动窗口/进程/程序(win32/64).已经阅读了关于pywinauto和SendKeys的信息,但是他们都在发送密钥之前激活了窗口.

有没有办法使用非活动窗口而不激活它?

如果有人发布简单的示例/片段会很棒.

谢谢.

小智 14

这是一个非常古老的帖子,但这里没有答案,我正在寻找与此类似的东西,我花了6个小时浏览Stackoverflow,最后只是阅读所有的C文档,因为它更有用.

<python>
#you will need the win32 libraries for this snippet of code to work, Links below
import win32gui
import win32con
import win32api
from time import sleep

#[hwnd] No matter what people tell you, this is the handle meaning unique ID, 
#["Notepad"] This is the application main/parent name, an easy way to check for examples is in Task Manager
#["test - Notepad"] This is the application sub/child name, an easy way to check for examples is in Task Manager clicking dropdown arrow
#hwndMain = win32gui.FindWindow("Notepad", "test - Notepad") this returns the main/parent Unique ID
hwndMain = win32gui.FindWindow("Notepad", "test - Notepad")

#["hwndMain"] this is the main/parent Unique ID used to get the sub/child Unique ID
#[win32con.GW_CHILD] I havent tested it full, but this DOES get a sub/child Unique ID, if there are multiple you'd have too loop through it, or look for other documention, or i may edit this at some point ;)
#hwndChild = win32gui.GetWindow(hwndMain, win32con.GW_CHILD) this returns the sub/child Unique ID
hwndChild = win32gui.GetWindow(hwndMain, win32con.GW_CHILD)

#print(hwndMain) #you can use this to see main/parent Unique ID
#print(hwndChild)  #you can use this to see sub/child Unique ID

#While(True) Will always run and continue to run indefinitely
while(True):
    #[hwndChild] this is the Unique ID of the sub/child application/proccess
    #[win32con.WM_CHAR] This sets what PostMessage Expects for input theres KeyDown and KeyUp as well
    #[0x44] hex code for D
    #[0]No clue, good luck!
    #temp = win32api.PostMessage(hwndChild, win32con.WM_CHAR, 0x44, 0) returns key sent
    temp = win32api.PostMessage(hwndChild, win32con.WM_CHAR, 0x44, 0)

    #print(temp) prints the returned value of temp, into the console
    print(temp)
    #sleep(1) this waits 1 second before looping through again
    sleep(1)
</python>
Run Code Online (Sandbox Code Playgroud)

我看过各地的帖子都可以使用

hwndEdit = win32gui.FindWindowEx(hwndMain, hwndChild, "Edit", "test - Notepad");
Run Code Online (Sandbox Code Playgroud)

但我永远无法理解.除此之外,微软网站上的所有文档都有不同的含义,所以我添加了自己的理解.

这应该让你开始,应该对其他人有所帮助.如果其他人有修改,请告诉我.

Win32 Python库

  • 有用:这里是“D”键以外的其他键的键码:https://docs.microsoft.com/en-us/windows/desktop/inputdev/virtual-key-codes (3认同)