使用 win32com.client 的 AppActivate 根据 ID 将焦点设置到窗口 [英] Set focus to window based on ID using win32com.client's AppActivate

查看:53
本文介绍了使用 win32com.client 的 AppActivate 根据 ID 将焦点设置到窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了以下操作,但是在脚本运行时焦点没有返回到具有焦点的程序:

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

推荐答案

事实证明 win32gui.GetForegroundWindow() 返回的是窗口句柄而不是进程 ID.

It turns out that win32gui.GetForegroundWindow() returns the window handle and not the process ID.

win32process.GetWindowThreadProcessId(hwnd) 可用于从句柄中获取线程 ID 和进程 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)

这篇关于使用 win32com.client 的 AppActivate 根据 ID 将焦点设置到窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆