使用 win32com.client 的 AppActivate 根据 ID 将焦点设置到窗口

发布于 2024-12-15 03:58:42 字数 290 浏览 4 评论 0原文

我已尝试以下操作,但焦点没有返回到运行脚本时具有焦点的程序:

import win32com.client
import win32gui

current = win32gui.GetForegroundWindow()

shell = win32com.client.Dispatch("WScript.Shell")

shell.AppActivate('Console2')

shell.SendKeys('{UP}{ENTER}')

shell.AppActivate(str(current))

I've tried the following, but focus isn't returned to the program that had focus when the script was run:

import win32com.client
import win32gui

current = win32gui.GetForegroundWindow()

shell = win32com.client.Dispatch("WScript.Shell")

shell.AppActivate('Console2')

shell.SendKeys('{UP}{ENTER}')

shell.AppActivate(str(current))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

公布 2024-12-22 03:58:42

事实证明,win32gui.GetForegroundWindow() 返回的是窗口句柄,而不是进程 ID。

win32process.GetWindowThreadProcessId(hwnd) 可用于从句柄中获取线程 ID 和进程 ID。

import win32com.client
import win32gui
import win32process

hwnd = win32gui.GetForegroundWindow()

_, pid = win32process.GetWindowThreadProcessId(hwnd)

shell = win32com.client.Dispatch("WScript.Shell")

shell.AppActivate('Console2')
shell.SendKeys('{UP}{ENTER}')

shell.AppActivate(pid)

It turns out that win32gui.GetForegroundWindow() returns the window handle and not the process ID.

win32process.GetWindowThreadProcessId(hwnd) can be used to get the thread ID and process ID from the handle.

import win32com.client
import win32gui
import win32process

hwnd = win32gui.GetForegroundWindow()

_, pid = win32process.GetWindowThreadProcessId(hwnd)

shell = win32com.client.Dispatch("WScript.Shell")

shell.AppActivate('Console2')
shell.SendKeys('{UP}{ENTER}')

shell.AppActivate(pid)
番薯 2024-12-22 03:58:42

没有足够的代表对此发表评论

除了 Acorn 的回答(很久以前)之外,您现在应该能够使用 SetFocus(handle)。

import win32com.client
import win32gui

hwnd = win32gui.GetForegroundWindow()

shell = win32com.client.Dispatch("WScript.Shell")

shell.AppActivate('Console2')
shell.SendKeys('{UP}{ENTER}')

win32gui.SetForegroundWindow(hwnd)

资料来源: http://timgolden.me.uk/pywin32-docs/win32gui__SetFocus_meth.html< /a>

Not enough rep to comment this

In addition to Acorn's answer (so long ago), you should now be able to use SetFocus(handle).

import win32com.client
import win32gui

hwnd = win32gui.GetForegroundWindow()

shell = win32com.client.Dispatch("WScript.Shell")

shell.AppActivate('Console2')
shell.SendKeys('{UP}{ENTER}')

win32gui.SetForegroundWindow(hwnd)

Source: http://timgolden.me.uk/pywin32-docs/win32gui__SetFocus_meth.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文