Pywinauto:无法将窗口置于前台

2024-05-13 12:11:43 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python驱动的自动化工具。

假设有一个应用程序池正在运行:

APPS_POOL = ['Chrome', 'SomeApp', 'Foo']

脚本在循环中运行(每秒),需要在它们之间随机切换:

# Init App object
app = application.Application()

# Select random app from the pull of apps
random_app = random.choice(APPS_POOL)
app.connect(title_re=".*%s" % random_app)
print 'Select "%s"' % random_app

# Access app's window object
app_dialog = app.window_(title_re=".*%s.*" % random_app)

if app_dialog.Exists():
    app_dialog.SetFocus()

第一次它工作得很好,但每一次-窗口不会被带到前台。有什么想法吗?

编辑:脚本从Win7 CMD运行。一旦焦点被设置到另一个窗口,系统是否可能以某种方式阻止命令设置焦点?


Tags: apps工具re脚本app应用程序objecttitle
3条回答

我认为SetFocus有点麻烦。至少在我的机器上我得到了一个错误:error: (87, 'AttachThreadInput', 'The parameter is incorrect.')。所以也许你可以玩最小化/恢复。注意,这种方法也不是防弹的。

import random
import time
from pywinauto import application
from pywinauto.findwindows import WindowAmbiguousError, WindowNotFoundError

APPS_POOL = ['Chrome', 'GVIM', 'Notepad', 'Calculator', 'SourceTree', 'Outlook']


# Select random app from the pull of apps
def show_rand_app():
    # Init App object
    app = application.Application()

    random_app = random.choice(APPS_POOL)
    try:
        print 'Select "%s"' % random_app
        app.connect(title_re=".*%s.*" % random_app)

        # Access app's window object
        app_dialog = app.top_window_()

        app_dialog.Minimize()
        app_dialog.Restore()
        #app_dialog.SetFocus()
    except(WindowNotFoundError):
        print '"%s" not found' % random_app
        pass
    except(WindowAmbiguousError):
        print 'There are too many "%s" windows found' % random_app
        pass

for i in range(15):
    show_rand_app()
    time.sleep(0.3)

接受的答案在某些情况下无法正常工作-一些基于Qt4-5的应用程序在某些原因下无法正确加载GUI。所以,我找到了SetFocus()错误的另一个解决方法。

from pywinauto import Application, win32defines
from pywinauto.win32functions import SetForegroundWindow, ShowWindow

app = Application().connect(path="C:\path\to\process.exe")
w = app.top_window()

#bring window into foreground
if w.HasStyle(win32defines.WS_MINIMIZE): # if minimized
    ShowWindow(w.wrapper_object(), 9) # restore window state
else:
    SetForegroundWindow(w.wrapper_object()) #bring to front

上面一个是完美的答案,但是HasStyle被否决了新方法如下

if m.has_style(win32defines.WS_MINIMIZE): # if minimized
    ShowWindow(m.wrapper_object(), 9) # restore window state
else:
    SetForegroundWindow(m.wrapper_object()) #bring to front

。。。。。。 另一种交易方式。。

app = Application(backend='win32').connect(path="")
app.top_window().set_focus()

相关问题 更多 >