我试图编写一个程序,通过搜索窗口的标题来查找窗口。一旦找到窗户,它就会试图把它带到前面。我正在使用win32gui
API来实现这一点。我可以让它在大部分情况下工作,但由于某种原因,如果任务管理器在前面,它就不工作了。我有下面的示例代码。
import win32gui, win32con
import re, traceback
from time import sleep
class cWindow:
def __init__(self):
self._hwnd = None
def BringToTop(self):
win32gui.BringWindowToTop(self._hwnd)
def SetAsForegroundWindow(self):
win32gui.SetForegroundWindow(self._hwnd)
def Maximize(self):
win32gui.ShowWindow(self._hwnd, win32con.SW_MAXIMIZE)
def setActWin(self):
win32gui.SetActiveWindow(self._hwnd)
def _window_enum_callback(self, hwnd, wildcard):
'''Pass to win32gui.EnumWindows() to check all the opened windows'''
if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
self._hwnd = hwnd
def find_window_wildcard(self, wildcard):
self._hwnd = None
win32gui.EnumWindows(self._window_enum_callback, wildcard)
def main():
sleep(5)
try:
wildcard = ".*Building Operation WorkStation.*"
cW = cWindow()
cW.find_window_wildcard(wildcard)
cW.Maximize()
cW.BringToTop()
cW.SetAsForegroundWindow()
except:
f = open("log.txt", "w")
f.write(traceback.format_exc())
print traceback.format_exc()
main()
我从多个在线来源拼凑而成。它似乎在大多数情况下都能工作,但对于某些窗口(如任务管理器),它有时会工作,但其他窗口则会失败。当它不能正常工作时,我只注意到应用程序图标呈黄色闪烁。有没有正确的方法来确保我感兴趣的窗口被设置为100%的前景?我不确定这是否相关,但我正在使用Windows7Professional(32位)和ServicePack1。
我找到了一个解决方案:如果是taskmanager,那就杀了它。我向
cWindow
添加了一个方法:在
cW = cWindow()
之后调用此方法。另一个错误陷阱是在
SetAsForegroundWindow
中防止此异常:只需在win32gui调用之前发送alt键:
最后,如果可以的话,不要比较
!= None
而是is not None
。更多的Python;)这是完整的代码:
资料来源:how do I close window with handle using win32gui in Python和win32gui.SetActiveWindow() ERROR : The specified procedure could not be found。
注意:以下仅涉及在激活窗口之前确保始终位于顶部的窗口(如任务管理器)处于隐藏状态-它假设激活部分本身工作正常(可能不是这样)。允许进程调用
SetForegroundWindow
Windows API函数的条件列在here。任务管理器在两个方面很特别:
Options > Always on Top
unchecked),您也可以让它显示在其他的顶部窗口上(这是普通窗口似乎无法做到的)。您的代码:
特别检查是否存在“任务管理器”窗口并将其最小化是一个选项,但请注意,可能会有其他始终在顶部窗口,因此要获得可靠的解决方案,您必须确定所有始终在顶部窗口打开并将其最小化:
下面的代码试图识别除任务栏和“开始”按钮之外的所有始终位于顶部的窗口,并且最小化了任何此类窗口。
新方法是
hide_always_on_top_windows
和_window_enum_callback_hide
。相关问题 更多 >
编程相关推荐