2011-11-11 39 views

回答

1

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