当任务管理器的窗口处于焦点状态时,如何使用键盘焦点将应用程序的窗口焦点对准前景?

如何解决当任务管理器的窗口处于焦点状态时,如何使用键盘焦点将应用程序的窗口焦点对准前景?

我有一个Python脚本,可以创建应用程序的实例并显示应用程序的窗口。

我正在尝试激活/聚焦窗口,以便将其置于前景/顶部并具有键盘输入焦点。

下面的代码通常可以正常工作,但是当在执行代码之前打开任务管理器的窗口并对其进行聚焦时,应用程序的窗口将显示在任务管理器下方,任务管理器将保持键盘输入焦点。

代码中的注释是我试图绕过也不起作用的特定问题的尝试。仅当将SwitchToThisWindow与{{1}一起使用FalseSetWindowPosHWND_TOPMOST一起使用(将窗口设置为最顶部)时,该窗口才会出现在任务管理器窗口的顶部,但是任务管理器仍然保持键盘输入焦点。

def bring_window_to_top(window_handle):
  import ctypes
  # import win32com.client
  # from win32con import HWND_TOP,HWND_TOPMOST,SWP_NOMOVE,SWP_NOSIZE

  current_thread_id = ctypes.windll.kernel32.GetCurrentThreadId()
  foreground_window_handle = ctypes.windll.user32.GetForegroundWindow()
  foreground_thread_id = ctypes.windll.user32.GetWindowThreadProcessId(foreground_window_handle,None)
  ctypes.windll.user32.AttachThreadInput(current_thread_id,foreground_thread_id,True)
  ctypes.windll.user32.BringWindowToTop(window_handle)
  # ctypes.windll.user32.SwitchToThisWindow(window_handle,True)
  # ctypes.windll.user32.SwitchToThisWindow(window_handle,False)
  # ctypes.windll.user32.SetWindowPos(window_handle,SWP_NOMOVE | SWP_NOSIZE)
  # ctypes.windll.user32.SetWindowPos(window_handle,HWND_TOP,SWP_NOMOVE | SWP_NOSIZE)
  # wscript_shell = win32com.client.Dispatch('WScript.Shell')
  # wscript_shell.SendKeys('%')
  # ctypes.windll.user32.SetForegroundWindow(window_handle)
  # ctypes.windll.user32.SetFocus(window_handle)
  # ctypes.windll.user32.SetActiveWindow(window_handle)
  # ctypes.windll.user32.AttachThreadInput(current_thread_id,False)

我也尝试使用功能AllowSetForegroundWindowLockSetForegroundWindowSystemParametersInfoW来将SPI_SETFOREGROUNDLOCKTIMEOUT设置为0,但出现错误Access denied.来自ctypes.FormatError()

有什么办法可以实现?

解决方法

您需要在清单中将UIAccess设置为true,以支持辅助功能。

以UIAccess权限启动的进程具有以下内容 能力:

  • 设置前景窗口。
  • 使用SendInput函数驱动任何应用程序窗口。
  • 通过使用低级挂钩,原始输入,GetKeyState,GetAsyncKeyState和GetKeyboardInput,将读取输入用于所有完整性级别。
  • 设置日记帐挂钩。
  • 使用AttachThreadInput将线程附加到更高完整性的输入队列。

首先,在清单中设置uiAccess=true

然后,签名代码。

最后,将其放在文件系统上的安全位置:

  • \ Program Files \包括子目录
  • \ Windows \ system32 \
  • \ Program Files(x86)\,包括64位版本的 Windows

您可以参考this documentthis answer

更新:

要将UIAccess设置为python脚本:

  1. 安装PyInstaller:pip install pyinstaller
  2. 使用Pyinstaller从Python脚本生成可执行文件。

这是我的测试示例,它设置了一个5秒的计时器以将窗口移至顶部。

hello.pyw:

import win32api,win32con,win32gui
import ctypes
class MyWindow:
        
    def __init__(self):
        win32gui.InitCommonControls()
        self.hinst = win32api.GetModuleHandle(None)
        className = 'MyWndClass'
        message_map = {
            win32con.WM_DESTROY: self.OnDestroy,win32con.WM_TIMER: self.OnTimer,}
        wndcls = win32gui.WNDCLASS()
        wndcls.style = win32con.CS_HREDRAW | win32con.CS_VREDRAW
        wndcls.lpfnWndProc = message_map
        wndcls.lpszClassName = className
        win32gui.RegisterClass(wndcls)
        style = win32con.WS_OVERLAPPEDWINDOW
        self.hwnd = win32gui.CreateWindow(
            className,'Title',style,win32con.CW_USEDEFAULT,500,self.hinst,None
        )
        win32gui.UpdateWindow(self.hwnd)
        win32gui.ShowWindow(self.hwnd,win32con.SW_SHOW)
        ctypes.windll.user32.SetTimer(self.hwnd,1,5000,0)
    def OnDestroy(self,hwnd,message,wparam,lparam):
        win32gui.PostQuitMessage(0)
        return True
    def OnTimer(self,lparam):
        current_thread_id = ctypes.windll.kernel32.GetCurrentThreadId()
        foreground_window_handle = ctypes.windll.user32.GetForegroundWindow()
        foreground_thread_id = ctypes.windll.user32.GetWindowThreadProcessId(foreground_window_handle,None)
        ctypes.windll.user32.BringWindowToTop(hwnd)
        return True

w = MyWindow()
win32gui.PumpMessages()

使用--manifest <FILE or XML>选项或直接使用pyinstaller --uac-uiaccess hello.pyw,则exe文件位于dist\\hello

  1. 创建证书并签名应用程序,进行抽样(不要忘记将证书安装到受信任的根证书颁发机构):https://stackoverflow.com/a/63193360/10611792
  2. 将其放置在文件系统上的安全位置,例如,我将dist\\hello放入了C:\\Program Files

结果:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-