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

2024-05-19 20:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试了以下操作,但运行脚本时焦点不会返回到具有焦点的程序:

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

Tags: import程序脚本clientcurrentshellwin32com焦点
1条回答
网友
1楼 · 发布于 2024-05-19 20:12:44

结果是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)

相关问题 更多 >