Pywinauto: unable to bring window to foreground
<p>Working on the Python-powered automation tool.</p>

<p>Imagine there is a pool of apps running:</p>

<pre><code>APPS_POOL = ['Chrome', 'SomeApp', 'Foo']
</code></pre>

<p>The script runs in the loop (every second) and needs to switch randomly between them:</p>

<pre><code># 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()
</code></pre>

<p>The first time it works fine, but every other - the window would not be brought into foreground. Any ideas?</p>

<p><strong>EDIT:</strong> the script is ran from Win7 CMD. Is it possible the system "blocks" CMD from setting focus somehow, once focus is set to other window?</p>

<p>I think the <code>SetFocus</code> is a bit buggy. At least on my machine I get an error: <code>error: (87, 'AttachThreadInput', 'The parameter is incorrect.')</code>. So maybe you can play with Minimize/Restore. Notice that this approach is not bullet proof either.</p>

<pre><code>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)
</code></pre>

python pywinauto