从启动过程中获取窗口处理程序

时间:2013-06-24 09:51:09

标签: python pywin32

我看到有win32process.GetWindowThreadProcess()获取窗口处理程序并返回它的进程ID。有没有办法做相反的事情:通过它的进程ID获取正在运行的进程的窗口处理程序?像win32gui.GetWindowHandler(processId)

这样的东西

特别是我要做的事情:

我有一个运行外部程序的python脚本,比方说notepad.exe。
调用runProgram()方法时会触发记事本。我想阻止此方法多次运行记事本我使用win32process以下列方式完成此操作:

import win32process as process
import sys

PORTABLE_APPLICATION_LOCATION = "C:\\Windows\\system32\\notepad.exe"
processHandler = -1

def runProgram():
    global processHandler
    #don't run a process more than once
    if (isLiveProcess(processHandler)):
        #Bring focus back to running window!
        return;
    try:
        startObj = process.STARTUPINFO()
        myProcessTuple = process.CreateProcess(PORTABLE_APPLICATION_LOCATION,None,None,None,8,8,None,None,startObj)
        processHandler = myProcessTuple[2]
    except:
        print(sys.exc_info[0])

def isLiveProcess(processHandler): #Process handler is dwProcessId
    processList = process.EnumProcesses()
    for aProcess in processList:
        if (aProcess == processHandler):
            return True
    return False

runProgram()

这可以按预期工作,但如果发现该进程已经存在,我想用win32gui

将它的窗口带回到前面

1 个答案:

答案 0 :(得分:2)

我不认为Windows API为此提供了一种方法,但您可以遍历所有打开的窗口,找到属于您的窗口。

我修改了你的程序,看起来像这样:

import win32process
import win32process as process
import win32gui
import sys

PORTABLE_APPLICATION_LOCATION = "C:\\Windows\\system32\\notepad.exe"
processHandler = -1


def callback(hwnd, procid):
    if procid in  win32process.GetWindowThreadProcessId(hwnd):
        win32gui.SetForegroundWindow(hwnd)

def show_window_by_process(procid):
    win32gui.EnumWindows(callback, procid)


def runProgram():
    global processHandler
    #don't run a process more than once
    if (isLiveProcess(processHandler)):
        #Bring focus back to running window!
        show_window_by_process(processHandler)
        return;
    try:
        startObj = process.STARTUPINFO()
        myProcessTuple = process.CreateProcess(PORTABLE_APPLICATION_LOCATION,None,None,None,8,8,None,None,startObj)
        processHandler = myProcessTuple[2]
    except:
        print(sys.exc_info[0])

def isLiveProcess(processHandler): #Process handler is dwProcessId
    processList = process.EnumProcesses()
    for aProcess in processList:
        if (aProcess == processHandler):
            return True
    return False

 runProgram()