我试过以下方法,但焦点没有返回到脚本运行时有焦点的程序上。
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))
结果发现 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)
没有足够的回复来评论这个
除了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)
来源于:/timgolden.me.ukpywin32-docswin32gui__。http:/timgolden.me.ukpywin32-docswin32gui__SetFocus_meth.html。