通过win32gui实现:
import win32gui, win32con, win32process,win32api
class Op():
def __init__(self, pid, tid, name):
self.pid = pid
self.tid = tid
self.name = name
def setForegroundWindowByWin32GUI(self):
hwnds = self.get_obj_hwnd()
hwnd = hwnds[0]
hForeWnd = win32gui.GetForegroundWindow()
FormThreadID = win32api.GetCurrentThreadId()
CWndThreadID = win32process.GetWindowThreadProcessId(hForeWnd)
win32process.AttachThreadInput(CWndThreadID[0], FormThreadID, True)
win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
result = win32gui.SetForegroundWindow(hwnd)
win32process.AttachThreadInput(CWndThreadID[0], FormThreadID, True)
if result:
return True
else:
return False
def get_obj_hwnd(self):
def _EnumWindowsCallback(hwnd, hwnds):
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self.pid and TId == self.tid:
if not win32gui.GetParent(hwnd) and win32gui.IsWindowVisible(hwnd):
hwnd_by_findWindow = win32gui.FindWindow(None,self.name)
if hwnd != hwnd_by_findWindow:
print('Game[{}]: hwnd_by_findWindow[{}] not equal, hwnd may be error'.format(self.name, hwnd_by_findWindow))
hwnds.append(hwnd)
hwnds = []
win32gui.EnumWindows(_EnumWindowsCallback, hwnds)
return hwnds
不通过win32gui这个第三方库实现:
class Op():
def __init__(self, pid, tid, name):
self.pid = pid
self.tid = tid
self.name = name
def setForegroundWindow(self):
hwnds = self.get_obj_hwnd_with_syspkg()
hwnd = hwnds[0]
hForeWnd = windll.user32.GetForegroundWindow()
FormThreadID = win32api.GetCurrentThreadId()
CWndThreadID = win32process.GetWindowThreadProcessId(hForeWnd)
win32process.AttachThreadInput(CWndThreadID[0], FormThreadID, True)
windll.user32.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
result = windll.user32.SetForegroundWindow(hwnd)
win32process.AttachThreadInput(CWndThreadID[0], FormThreadID, True)
if result:
return True
else:
return False
def get_obj_hwnd_with_syspkg(self):
hwnds = []
def _EnumWindowsCallback(hwnd, lParam):
TId, PId = win32process.GetWindowThreadProcessId(hwnd)
if PId == self._pid and TId == self._tid:
if not windll.user32.GetParent(hwnd) and windll.user32.IsWindowVisible(hwnd):
hwnd_by_findWindow = windll.user32.FindWindowW(self.name, None)
if hwnd != hwnd_by_findWindow:
print('Game[{}]: hwnd_by_findWindow[{}] not equal, hwnd may be error'.format(self.name, hwnd_by_findWindow))
hwnds.append(hwnd)
EnumWindows = windll.user32.EnumWindows
pFunc = WINFUNCTYPE(c_int, HWND, LPARAM)
pFuncHandle = pFunc(_EnumWindowsCallback)
EnumWindows(pFuncHandle, None)
return hwnds