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.
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.