Python win32gui SetAsForegroundWindow函数无法正常工作 [英] Python win32gui SetAsForegroundWindow function not working properly

查看:1014
本文介绍了Python win32gui SetAsForegroundWindow函数无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个通过搜索窗口标题来查找窗口的程序.找到窗口后,它将尝试将其移到最前面.我正在使用win32gui API来实现这一目标.我能够使它在大多数情况下正常工作,但是由于某些原因,如果任务管理器在前面,它将无法正常工作.我有以下示例代码.

I am trying to write a program that finds a window by searching for its title. Once it has found the window, it will attempt to bring it to front. I am using win32gui API to achieve this. I am able to get it to work for the most part, but for some reason it does not work if the taskmanager is in front. I have the follow sample code.

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%的前景?我不确定这是否相关,但是我正在使用Windows 7 Professional(32位)和Service Pack1.

I pieced this together from multiple online sources. It seems to work for the most part but for some windows like the task manager, it'll work sometimes but fails the rest. When it doesnt work properly, all I notice is the application icon blinks yellow. Is there a proper way of doing this to make sure the window that I am interested in is set to foreground 100% of the times? I am not sure if this is relevant but I am using Windows 7 Professional (32-bit) with Service Pack 1.

推荐答案

我找到了一个解决方案:如果是taskmanager,则将其杀死.我向cWindow添加了一种方法:

I found a solution: if taskmanager, then kill it. I added a method to 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中的此异常:

Another bug trap is to prevent this exception in SetAsForegroundWindow:

error: (0, 'SetForegroundWindow', 'No error message is available')

只需在win32gui调用之前发送一个alt键:

just send an alt key before the win32gui call:

# Add this import
import win32com.client

# Add this to __ini__
self.shell = win32com.client.Dispatch("WScript.Shell")

# And SetAsForegroundWindow becomes
def SetAsForegroundWindow(self):
    self.shell.SendKeys('%')
    win32gui.SetForegroundWindow(self._hwnd)

最后,如果可以的话,请不要将!= None进行比较,而是将is not None进行比较.更多pythonic;)

Last, if I may, do not compare != None but is not None. More pythonic ;)

这是完整的代码:

# coding: utf-8

import re, traceback
import win32gui, win32con, win32com.client
from time import sleep


class 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的句柄​​ win32gui .SetActiveWindow()错误:找不到指定的过程.

这篇关于Python win32gui SetAsForegroundWindow函数无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆