我找到了解决方案:如果是taskmanager,则将其杀死。我添加了一个方法
cWindow:
def kill_task_manager(self): # Here I use your method to find a window because of an accent in my french OS, # but you should use win32gui.FindWindow(None, 'Task Manager complete name'). wildcard = 'Gestionnaire des t.+ches de Windows' self.find_window_wildcard(wildcard) if self._hwnd: win32gui.PostMessage(self._hwnd, win32con.WM_CLOSE, 0, 0) # kill it sleep(0.5) # important to let time for the window to be closed
在之后调用此方法
cW = cWindow()。
另一个错误陷阱是防止出现以下情况中的异常
SetAsForegroundWindow:
error: (0, 'SetForegroundWindow', 'No error message is available')
只需在win32gui调用之前发送一个alt键:
# Add this importimport win32com.client# Add this to __ini__self.shell = win32com.client.Dispatch("Wscript.Shell")# And SetAsForegroundWindow becomesdef SetAsForegroundWindow(self): self.shell.SendKeys('%') win32gui.SetForegroundWindow(self._hwnd)最后,如果我可以,不比较
!= None,但是
is not None。更多pythonic;)
这是完整的代码:
# coding: utf-8import re, tracebackimport win32gui, win32con, win32com.clientfrom time import sleepclass cWindow: def __init__(self): self._hwnd = None self.shell = win32com.client.Dispatch("Wscript.Shell") def BringToTop(self): win32gui.BringWindowToTop(self._hwnd) def SetAsForegroundWindow(self): self.shell.SendKeys('%') 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))) is not None: self._hwnd = hwnd def find_window_wildcard(self, wildcard): self._hwnd = None win32gui.EnumWindows(self._window_enum_callback, wildcard) def kill_task_manager(self): wildcard = 'Gestionnaire des t.+ches de Windows' self.find_window_wildcard(wildcard) if self._hwnd: win32gui.PostMessage(self._hwnd, win32con.WM_CLOSE, 0, 0) sleep(0.5)def main(): sleep(5) try: wildcard = ".*Building Operation WorkStation.*" cW = cWindow() cW.kill_task_manager() cW.find_window_wildcard(wildcard) cW.BringToTop() cW.Maximize() cW.SetAsForegroundWindow() except: f = open("log.txt", "w") f.write(traceback.format_exc()) print(traceback.format_exc())if __name__ == '__main__': main()资料来源:如何在Python和win32gui.SetActiveWindow()中使用win32gui关闭带有句柄的窗口错误:找不到指定的过程。



