<p>注意:以下<strong>仅涉及在激活窗口之前确保始终位于顶部的窗口(如任务管理器)处于隐藏状态-它假设激活部分本身工作正常(可能不是这样)。允许进程调用<code>SetForegroundWindow</code>Windows API函数的条件列在<a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms633539(v=vs.85).aspx" rel="noreferrer">here</a>。</p>
<hr/>
<p>任务管理器在两个方面很特别:</p>
<ul>
<li>默认情况下,它设置为始终在顶部显示<em>,即高于所有其他窗口。</li>
<li>即使关闭(<code>Options > Always on Top</code><em>unchecked</em>),您也可以让它显示在<em>其他</em>的顶部窗口上(这是普通窗口似乎无法做到的)。</li>
</ul>
<p>您的代码:</p>
<ul>
<li><em>在我的测试中,目标窗口确实变成了活动窗口。</li>
<li>是指任务管理器窗口仍然位于(最大化)窗口的顶部,而不是工作。
<ul>
<li>不幸的是,即使试图让<em>你的</em>窗口也成为一个始终位于顶部的窗口也无济于事。</li>
</ul></li>
</ul>
<p>特别检查是否存在“任务管理器”窗口并将其最小化是一个选项,但请注意,可能会有<em>其他</em>始终在顶部窗口,因此<strong>要获得可靠的解决方案,您必须确定<em>所有</em>始终在顶部窗口打开并将其最小化:</p>
<p>下面的代码试图识别除任务栏和“开始”按钮之外的所有始终位于顶部的窗口,并且<em>最小化了任何此类窗口。</p>
<p>新方法是<code>hide_always_on_top_windows</code>和<code>_window_enum_callback_hide</code>。</p>
<pre><code>import win32gui, win32con
import re, traceback
from time import sleep
class cWindow:
def __init__(self):
self._hwnd = None
def SetAsForegroundWindow(self):
# First, make sure all (other) always-on-top windows are hidden.
self.hide_always_on_top_windows()
win32gui.SetForegroundWindow(self._hwnd)
def Maximize(self):
win32gui.ShowWindow(self._hwnd, win32con.SW_MAXIMIZE)
def _window_enum_callback(self, hwnd, regex):
'''Pass to win32gui.EnumWindows() to check all open windows'''
if self._hwnd is None and re.match(regex, str(win32gui.GetWindowText(hwnd))) is not None:
self._hwnd = hwnd
def find_window_regex(self, regex):
self._hwnd = None
win32gui.EnumWindows(self._window_enum_callback, regex)
def hide_always_on_top_windows(self):
win32gui.EnumWindows(self._window_enum_callback_hide, None)
def _window_enum_callback_hide(self, hwnd, unused):
if hwnd != self._hwnd: # ignore self
# Is the window visible and marked as an always-on-top (topmost) window?
if win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) & win32con.WS_EX_TOPMOST:
# Ignore windows of class 'Button' (the Start button overlay) and
# 'Shell_TrayWnd' (the Task Bar).
className = win32gui.GetClassName(hwnd)
if not (className == 'Button' or className == 'Shell_TrayWnd'):
# Force-minimize the window.
# Fortunately, this seems to work even with windows that
# have no Minimize button.
# Note that if we tried to hide the window with SW_HIDE,
# it would disappear from the Task Bar as well.
win32gui.ShowWindow(hwnd, win32con.SW_FORCEMINIMIZE)
def main():
sleep(5)
try:
regex = ".*Building Operation WorkStation.*"
cW = cWindow()
cW.find_window_regex(regex)
cW.Maximize()
cW.SetAsForegroundWindow()
except:
f = open("log.txt", "w")
f.write(traceback.format_exc())
print(traceback.format_exc())
main()
</code></pre>