Python: win32gui.SetForegroundWindow

2019-04-16 04:02发布

I have just written simple script to launch an applciation and I am trying to use "SendKeys" module to send keystrokes to this application. There is one "Snapshot" button, but I cant get Python to click "Snapshot" button, as the new window is not in focus. So I am planning to use Win32gui module's win32gui.FindWindow and win32gui.SetForegroundWindow functionality. But it gives me error- invalid handle. My app name is "DMCap"

Here is code snippet in Python:

handle = win32gui.FindWindow(0, "DMCap")  //paassing 0 as I dont know classname 
win32gui.SetForegroundWindow(handle)  //put the window in foreground

Can anyone help me? Is this Python code correct? Can I send handle directly like this?

标签: python handle
1条回答
对你真心纯属浪费
2楼-- · 2019-04-16 04:24

Your code should run just fine as-is, IF there is truly a window titled "DMCap." To get a list of handles and titles, run the code below:

import win32gui
def window_enum_handler(hwnd, resultList):
    if win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowText(hwnd) != '':
        resultList.append((hwnd, win32gui.GetWindowText(hwnd)))

def get_app_list(handles=[]):
    mlst=[]
    win32gui.EnumWindows(window_enum_handler, handles)
    for handle in handles:
        mlst.append(handle)
    return mlst

appwindows = get_app_list()
for i in appwindows:
    print i

This will produce a list of tuples containing handle, title pairs.

查看更多
登录 后发表回答