根据ID使用win32com.client的AppActivate设置窗口焦点
我试过以下方法,但在脚本运行时,焦点并没有返回到之前有焦点的程序上:
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))
2 个回答
0
没有足够的积分来评论这个
除了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
3
原来,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)