2017-06-12 24 views
-2

獲取HWND有沒有辦法得到容易通過procees HWND名 我可以很容易獲得通過WinTitle按進程名

hwnd = win32gui.FindWindow(None, "Notepad") 

HWND也許我可以通過進程名獲得一件容易的事?

hwnd = win32gui.FindHwndByProcessName(None, "notepad.exe") <---????? 

回答

2

這不能這麼容易做到。存在的主要問題:

  1. 可能有很多工藝名稱爲notepad.exe
  2. 一個流程可以有多個窗口。

因此,首先您需要獲取名稱爲notepad.exe的進程列表,然後獲取這些進程的窗口列表。另外,爲了簡單起見,我們可以假設您只有一個notepad.exe進程正在運行。

1.獲取進程列表給定名稱

可以使用psutil軟件包這一任務:

import psutil 

# A list of processes with a name notepad.exe: 
notepads = [item for item in psutil.process_iter() if item.name() == 'notepad.exe'] 
print(notepads) # [<psutil.Process(pid=4416, name='notepad.exe') at 64362512>] 

# pid of the first found notepad.exe process: 
pid = next(item for item in psutil.process_iter() if item.name() == 'notepad.exe').pid 
# (raises StopIteration exception if Notepad is not running) 

print(pid) # 4416 

2.獲取過程的窗口與給定pid

列表

要獲取屬於某個進程的窗口列表,您可以使用EnumWindows函數。

例如,我們需要獲得過程中的所有可見的窗口與pid = 4416

import win32gui 
import win32process 

def enum_window_callback(hwnd, pid): 
    tid, current_pid = win32process.GetWindowThreadProcessId(hwnd) 
    if pid == current_pid and win32gui.IsWindowVisible(hwnd): 
     windows.append(hwnd) 

# pid = 4416 # pid that we've got on the previous step 
windows = [] 

win32gui.EnumWindows(enum_window_callback, pid) 

# Now windows variable contains a list of hwnds of notepad 

# Output of captions of the found windows: 
print([win32gui.GetWindowText(item) for item in windows]) 

輸出:

['Unnamed — Notepad'] 

如果如記事本中的任何打開的對話。頁面設置,你還可以在窗口列表中找到它的句柄。