Recipe Grab Window Focus

ProjectThreepio edited this page Jun 8, 2017 · 2 revisions

Single-file noconsole executables have a problem where the main window doesn't have focus. I've found that if you call this function from your tkinter dialog code, your script's dialogs will be focused.

There are a few things to note--the time.sleep call is almost certainly a kludge, but it appears the GUI thread must be blocked for a bit in order for this to work. Also, Popen must be used instead of call, I believe because the external script must still be running when the function returns. Other things, like using start /min are just my attempt to make a minimally-visible helper window, since hidden windows failed to set window focus when I tried.

This is tested only on Windows/py3.4, there are definitely portability issues here.

def grab_focus():
    pid=os.getpid()
    vbscript_file="some_path.vbs"
    with open(vbscript_file, "w") as vbs_script:
        vbs_script.write("CreateObject(\"wscript.shell\").appactivate WScript.Arguments.Item(0)\n")
    arg_list=["start","/min","","cscript.exe", VBScriptFile, str(pid)]
    time.sleep(0.3)
    subprocess.Popen(arg_list, shell=True)
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.