概述
通过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
最后
以上就是结实大门为你收集整理的python之windows窗口置顶的全部内容,希望文章能够帮你解决python之windows窗口置顶所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复