-2
獲取HWND有沒有辦法得到容易通過procees HWND名 我可以很容易獲得通過WinTitle按進程名
hwnd = win32gui.FindWindow(None, "Notepad")
HWND也許我可以通過進程名獲得一件容易的事?
hwnd = win32gui.FindHwndByProcessName(None, "notepad.exe") <---?????
獲取HWND有沒有辦法得到容易通過procees HWND名 我可以很容易獲得通過WinTitle按進程名
hwnd = win32gui.FindWindow(None, "Notepad")
HWND也許我可以通過進程名獲得一件容易的事?
hwnd = win32gui.FindHwndByProcessName(None, "notepad.exe") <---?????
這不能這麼容易做到。存在的主要問題:
notepad.exe
因此,首先您需要獲取名稱爲notepad.exe
的進程列表,然後獲取這些進程的窗口列表。另外,爲了簡單起見,我們可以假設您只有一個notepad.exe
進程正在運行。
可以使用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
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']
如果如記事本中的任何打開的對話。頁面設置,你還可以在窗口列表中找到它的句柄。