简体   繁体   English

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

[英]Set focus to window based on ID using win32com.client's AppActivate

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

It turns out that win32gui.GetForegroundWindow() returns the window handle and not the process ID.结果是win32gui.GetForegroundWindow()返回窗口句柄而不是进程 ID。

win32process.GetWindowThreadProcessId(hwnd) can be used to get the thread ID and process ID from the handle. 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)

Not enough rep to comment this没有足够的代表对此发表评论

In addition to Acorn's answer (so long ago), you should now be able to use SetFocus(handle).除了 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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM