前言
工作中,同事隨口提了一句:要是能讓WPS窗口置頂就好了,老是將窗口切換來切換去的太麻煩了。
然后,這個奇怪的點子引起了本人的注意,那就試試能不能實現(xiàn)吧。
一、網上找到的代碼
不知道是不是我手法或版本的緣故,用了網上找的代碼都是窗口彈出而已,并沒有把它置頂,可以參考以下我嘗試過于借鑒得到的成功的博客:
Python中最全的窗口操作,如窗口最大化、最小化、窗口置頂、獲取縮放比例等
python選擇應用窗口到最前面
Python中設置指定窗口為前臺活動窗口(最頂層窗口)win32gui
二、嘗試與借鑒后的代碼——加入PyQt界面
1.引入庫
代碼如下(示例):
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
# 下面這個是我使用的ui界面代碼
from Window_top import Ui_MainWindow as UI_W
import win32gui
import win32con
import win32com.client
# 下面兩行代碼是用于解決圖標不顯示的問題
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")
2.主代碼
代碼如下(示例):
class MAIN_windows(UI_W, QMainWindow):
def __init__(self):
super(MAIN_windows, self).__init__()
self.hwnd_map = None
self.setupUi(self)
self.pushButton.clicked.connect(self.lll)
self.pushButton_2.clicked.connect(self.Window_top) # 選擇應用窗口置頂
self.pushButton_3.clicked.connect(self.cancel_Window_top) # 取消應用窗口置頂
def get_all_hwnd(self, hwnd, mouse):
"""
獲取后臺運行的所有程序
"""
if (win32gui.IsWindow(hwnd) and
win32gui.IsWindowEnabled(hwnd) and
win32gui.IsWindowVisible(hwnd)):
self.hwnd_map.update({hwnd: win32gui.GetWindowText(hwnd)})
def lll(self):
"""
顯示獲取到的所有程序。
(第一個顯示估計是程序運行的ID號)
(第二個顯示是程序窗口名與程序名)
"""
try:
self.hwnd_map = {}
win32gui.EnumWindows(self.get_all_hwnd, 0)
for i in self.hwnd_map.items():
if i[1] != "":
print(i)
self.textEdit_4.append(str(i[0]) + " " + str(i[1]))
except Exception as exx:
print("\nlll", exx)
def Window_top(self):
"""
設置指定窗口置頂
"""
try:
App_name = str(self.lineEdit.text())
for h, t in self.hwnd_map.items():
if t != "":
if t.find(App_name) != -1:
# h 為想要放到最前面的窗口句柄
print(h, t)
win32gui.BringWindowToTop(h)
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys('%')
# 被其他窗口遮擋,調用后放到最前面
win32gui.SetWindowPos(h, win32con.HWND_TOPMOST, 0, 0, 800, 600, win32con.SWP_SHOWWINDOW)
# 解決被最小化的情況
win32gui.ShowWindow(h, win32con.SW_RESTORE)
except Exception as ee:
print("\nWindow_top", ee)
def cancel_Window_top(self):
"""
取消指定窗口置頂
"""
try:
App_name = str(self.lineEdit.text())
for h, t in self.hwnd_map.items():
if t != "":
if t.find(App_name) != -1:
# h 為想要放到最前面的窗口句柄
print(h, t)
# win32gui.BringWindowToTop(h)
# shell = win32com.client.Dispatch("WScript.Shell")
# shell.SendKeys('%')
# 取消置頂
win32gui.SetWindowPos(h, win32con.HWND_NOTOPMOST, 0, 0, 800, 600, win32con.SWP_SHOWWINDOW)
# 解決被最小化的情況
win32gui.ShowWindow(h, win32con.SW_RESTORE)
except Exception as ee:
print("\ncancel_Window_top:", ee)
def closeEvent(self, event):
"""
軟件關閉時取消所有窗口置頂,
但還有些問題,開了多個窗口置頂后貌似沒能讓所有置頂?shù)拇翱诙既∠庙? """
try:
self.cancel_Window_top()
except Exception as ee:
print("\ncloseEvent:", ee)
if __name__ == "__main__":
try:
app = QApplication(sys.argv)
win = MAIN_windows()
win.show()
sys.exit(app.exec_())
except Exception as ex:
print('主函數(shù)入口出錯了:', ex)
啟動后點擊“顯示有哪些窗口可以置頂”就會得到類似下圖的界面
輸入的應用窗口名不需要輸全名,輸入一些特有的關鍵字即可,例如打開了Google Chrome,獲取到的應用名會包含正在訪問的頁面標題,顯示為“寫文章-CSDN博客 - Google Chrome”,那么在輸入欄中輸入“Google Chrome”或“Google”就行了。
針對WPS軟件的話,就直接輸入“WPS”即可。文章來源:http://www.zghlxwxcb.cn/news/detail-538208.html
3.完整主代碼
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
# 下面這個是我使用的ui界面代碼
from Window_top import Ui_MainWindow as UI_W
import win32gui
import win32con
import win32com.client
# 下面兩行代碼是用于解決圖標不顯示的問題
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")
class MAIN_windows(UI_W, QMainWindow):
def __init__(self):
super(MAIN_windows, self).__init__()
self.hwnd_map = None
self.setupUi(self)
self.pushButton.clicked.connect(self.lll)
self.pushButton_2.clicked.connect(self.Window_top) # 選擇應用窗口置頂
self.pushButton_3.clicked.connect(self.cancel_Window_top) # 取消應用窗口置頂
def get_all_hwnd(self, hwnd, mouse):
"""
獲取后臺運行的所有程序
"""
if (win32gui.IsWindow(hwnd) and
win32gui.IsWindowEnabled(hwnd) and
win32gui.IsWindowVisible(hwnd)):
self.hwnd_map.update({hwnd: win32gui.GetWindowText(hwnd)})
def lll(self):
"""
顯示獲取到的所有程序。
(第一個顯示估計是程序運行的ID號)
(第二個顯示是程序窗口名與程序名)
"""
try:
self.hwnd_map = {}
win32gui.EnumWindows(self.get_all_hwnd, 0)
for i in self.hwnd_map.items():
if i[1] != "":
print(i)
self.textEdit_4.append(str(i[0]) + " " + str(i[1]))
except Exception as exx:
print("\nlll", exx)
def Window_top(self):
"""
設置指定窗口置頂
"""
try:
App_name = str(self.lineEdit.text())
for h, t in self.hwnd_map.items():
if t != "":
if t.find(App_name) != -1:
# h 為想要放到最前面的窗口句柄
print(h, t)
win32gui.BringWindowToTop(h)
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys('%')
# 被其他窗口遮擋,調用后放到最前面
win32gui.SetWindowPos(h, win32con.HWND_TOPMOST, 0, 0, 800, 600, win32con.SWP_SHOWWINDOW)
# 解決被最小化的情況
win32gui.ShowWindow(h, win32con.SW_RESTORE)
except Exception as ee:
print("\nWindow_top", ee)
def cancel_Window_top(self):
"""
取消指定窗口置頂
"""
try:
App_name = str(self.lineEdit.text())
for h, t in self.hwnd_map.items():
if t != "":
if t.find(App_name) != -1:
# h 為想要放到最前面的窗口句柄
print(h, t)
# win32gui.BringWindowToTop(h)
# shell = win32com.client.Dispatch("WScript.Shell")
# shell.SendKeys('%')
# 取消置頂
win32gui.SetWindowPos(h, win32con.HWND_NOTOPMOST, 0, 0, 800, 600, win32con.SWP_SHOWWINDOW)
# 解決被最小化的情況
win32gui.ShowWindow(h, win32con.SW_RESTORE)
except Exception as ee:
print("\ncancel_Window_top:", ee)
def closeEvent(self, event):
"""
軟件關閉時取消所有窗口置頂,
但還有些問題,開了多個窗口置頂后貌似沒能讓所有置頂?shù)拇翱诙既∠庙? """
try:
self.cancel_Window_top()
except Exception as ee:
print("\ncloseEvent:", ee)
if __name__ == "__main__":
try:
app = QApplication(sys.argv)
win = MAIN_windows()
win.show()
sys.exit(app.exec_())
except Exception as ex:
print('主函數(shù)入口出錯了:', ex)
4.UI界面代碼
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
font = QtGui.QFont()
font.setPointSize(12)
MainWindow.setFont(font)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
font = QtGui.QFont()
font.setFamily("楷體")
font.setPointSize(14)
font.setBold(False)
font.setWeight(50)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 3)
self.textEdit_4 = QtWidgets.QTextEdit(self.centralwidget)
font = QtGui.QFont()
font.setFamily("楷體")
font.setPointSize(14)
self.textEdit_4.setFont(font)
self.textEdit_4.setObjectName("textEdit_4")
self.gridLayout.addWidget(self.textEdit_4, 1, 0, 1, 3)
self.label_9 = QtWidgets.QLabel(self.centralwidget)
font = QtGui.QFont()
font.setFamily("楷體")
font.setPointSize(14)
font.setBold(False)
font.setWeight(50)
self.label_9.setFont(font)
self.label_9.setObjectName("label_9")
self.gridLayout.addWidget(self.label_9, 2, 0, 1, 1)
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
font = QtGui.QFont()
font.setFamily("楷體")
font.setPointSize(14)
font.setBold(False)
font.setWeight(50)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName("lineEdit")
self.gridLayout.addWidget(self.lineEdit, 2, 1, 1, 2)
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
font = QtGui.QFont()
font.setFamily("楷體")
font.setPointSize(14)
font.setBold(False)
font.setWeight(50)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.gridLayout.addWidget(self.pushButton_2, 3, 0, 1, 2)
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
font = QtGui.QFont()
font.setFamily("楷體")
font.setPointSize(14)
font.setBold(False)
font.setWeight(50)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
self.gridLayout.addWidget(self.pushButton_3, 3, 2, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Window_top"))
self.pushButton.setText(_translate("MainWindow", "顯示有哪些窗口可以置頂"))
self.label_9.setText(_translate("MainWindow", "輸入置頂?shù)膽么翱诿?))
self.pushButton_2.setText(_translate("MainWindow", "確定置頂"))
self.pushButton_3.setText(_translate("MainWindow", "取消置頂"))
總結
代碼中還有些小bug,但不怎么影響使用。
當軟件關閉的時候,好像沒能讓所有置頂過的窗口取消置頂,所以最好是點擊界面右下角的“取消置頂”,不然很難讓那指定的窗口取消置頂。文章來源地址http://www.zghlxwxcb.cn/news/detail-538208.html
到了這里,關于Python使用PyQt5實現(xiàn)指定窗口置頂?shù)奈恼戮徒榻B完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!