4

我看到有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将其窗口重新置于前面

4

1 回答 1

4

我不认为 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()
于 2013-06-24T10:48:27.600 回答