【发布时间】:2020-12-06 10:56:57
【问题描述】:
我有一个 Python 脚本,它创建一个应用程序实例并显示应用程序的窗口。
我正在尝试激活/聚焦窗口,以便将其带到前台/顶部并获得键盘输入焦点。
下面的代码通常可以工作,但是在代码执行之前打开任务管理器的窗口并获得焦点时,应用程序的窗口出现在任务管理器的下方,并且任务管理器保持键盘输入焦点。
代码中的 cmets 是我试图规避特定问题的尝试,但也没有奏效。只有当SwitchToThisWindow与False或SetWindowPos与HWND_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, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE)
# ctypes.windll.user32.SetWindowPos(window_handle, HWND_TOP, 0, 0, 0, 0, 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, foreground_thread_id, False)
我也尝试使用函数AllowSetForegroundWindow、LockSetForegroundWindow 和SystemParametersInfoW 将SPI_SETFOREGROUNDLOCKTIMEOUT 设置为0,但我从ctypes.FormatError() 收到错误Access denied.。
有什么方法可以实现吗?
【问题讨论】:
标签: python winapi focus foreground