python - 使用 python 将一些键发送到非事件窗口

标签 python windows key send sendkeys

我正在尝试使用 Python 将一些 key 发送到非事件窗口/进程/程序 (Win32/64)。已经阅读过 pywinautoSendKeys,但它们都在发送 key 之前激活了窗口。

有没有办法在不激活窗口的情况下使用非事件窗口?

如果有人发布了一个简单的示例/代码段,那就太好了。

最佳答案

这是一篇非常古老的帖子,但这里没有答案,我一直在寻找完全像这样的东西,我花了 6 个小时浏览 Stackoverflow,最后只阅读了所有 C 文档,因为它更有用。

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

我已经看到了到处使用的帖子

hwndEdit = win32gui.FindWindowEx(hwndMain, hwndChild, "Edit", "test - Notepad");

但我一直想不通。此外,Microsoft 网站上的所有文档都模棱两可,因此我添加了我自己的理解方式。

这应该可以帮助您入门,并且应该对其他人有所帮助。如果其他人有任何修改,请告诉我。

Win32 Python Library

关于python - 使用 python 将一些键发送到非事件窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12996985/

相关文章:

javascript - HTML 文本输入 - 阻止 Windows 8 触摸键盘?

c# - 在 C# 中模拟按键

python 减去以秒为单位的时间增量

Python - 按首字母分隔列表

windows - 无法删除 Windows 上包含 .git 的文件夹

apache-flex - 弹性 : Simulate key press

arrays - 检查数组中索引或键的最简单方法?

python - 在 Python 中调用 getLogger 之前,我是否需要显式检查 __name__ == "__main__"?

python - 记录循环生成的数字

c++ - 无法使用CMake生成OpenCV项目