2013-06-24 68 views
2

我看到有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

回答

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() 
+0

是的,我看到在我的研究這個選項。這是有問題的,因爲應用程序的標題可能會有所不同:例如,打開文件可能會將記事本的標題從「Notepad.exe」更改爲「fileName.txt」。我正在考慮用processId而不是標題來實現這一點,只是想,也許有更直接的東西。 – user1555863

+0

乾杯,與此編輯完全是如何完成的。有一點值得注意:我的測試結果顯示'win32gui.ShowWindow(hwnd,1)'比'SetForegroundWindow(hwnd)'有更好的效果,似乎效果更好。 – user1555863