2016-09-30 271 views
3

使用Python驅動的自動化工具。Pywinauto:無法使窗口前景

想象有應用程序運行的池:

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運行。一旦焦點設置爲其他窗口,系統是否有可能以某種方式阻止CMD設置焦點?

回答

6

我認爲SetFocus是有點bug。至少在我的機器上出現錯誤:error: (87, 'AttachThreadInput', 'The parameter is incorrect.')。所以也許你可以玩Minimize/Restore。請注意,這種方法也不是防彈的。

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) 
+0

很好@vitswd,它的工作原理!看起來像'Focus()'的確有問題。另外,使用'try..except'的好主意。 – Oleg

+0

只是好奇,你是如何收到這個錯誤(控制檯,你嘗試調試)? – Oleg

+0

我在IPython中玩過你的代碼,當SetFocus在 – vitswd

1

接受的答案在某些情況下無法正常工作 - 某些基於Qt4-5的應用程序不會在某些原因下正確加載GUI。所以,我發現了另一個SetFocus()bug的解決方法。

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 
+0

上失敗時,我看到上面的錯誤。我看到Qt5應用程序(WireShark)的這個問題。將修復pywinauto 0.6.4。 –