Python使用PyQt5实现指定窗口置顶

这篇具有很好参考价值的文章主要介绍了Python使用PyQt5实现指定窗口置顶。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


前言

工作中,同事随口提了一句:要是能让WPS窗口置顶就好了,老是将窗口切换来切换去的太麻烦了。
然后,这个奇怪的点子引起了本人的注意,那就试试能不能实现吧。


一、网上找到的代码

不知道是不是我手法或版本的缘故,用了网上找的代码都是窗口弹出而已,并没有把它置顶,可以参考以下我尝试过于借鉴得到的成功的博客:
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):
        """
        软件关闭时取消所有窗口置顶,
        但还有些问题,开了多个窗口置顶后貌似没能让所有置顶的窗口都取消置顶
        """
        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('主函数入口出错了:', ex)

启动后点击“显示有哪些窗口可以置顶”就会得到类似下图的界面
pyqt5 窗口置顶,小小项目,Python的使用,python
输入的应用窗口名不需要输全名,输入一些特有的关键字即可,例如打开了Google Chrome,获取到的应用名会包含正在访问的页面标题,显示为“写文章-CSDN博客 - Google Chrome”,那么在输入栏中输入“Google Chrome”或“Google”就行了。
针对WPS软件的话,就直接输入“WPS”即可。


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):
        """
        软件关闭时取消所有窗口置顶,
        但还有些问题,开了多个窗口置顶后貌似没能让所有置顶的窗口都取消置顶
        """
        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('主函数入口出错了:', 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", "输入置顶的应用窗口名"))
        self.pushButton_2.setText(_translate("MainWindow", "确定置顶"))
        self.pushButton_3.setText(_translate("MainWindow", "取消置顶"))

总结

代码中还有些小bug,但不怎么影响使用。
当软件关闭的时候,好像没能让所有置顶过的窗口取消置顶,所以最好是点击界面右下角的“取消置顶”,不然很难让那指定的窗口取消置顶。文章来源地址https://www.toymoban.com/news/detail-538208.html

到了这里,关于Python使用PyQt5实现指定窗口置顶的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Python使用PyQt5实现计算平方或者立方

    此源码为直播时讲解的源码,我加了注释

    2024年02月11日
    浏览(27)
  • 使用VS Code Python和PYQT5实现简单的按键精灵

    创建工程目录,创建UI文件,创建Main Window 使用思维导图进行简单的需求整理 由于没怎么用过pyqt,简单排版一下,后续也可以再用Vertical Layout和Horizontal Layout进行排版优化,按设计,三个文本框进行-功能说明,-时间间隔填写,-状态说明的显示,一个按钮可以选择-删除文件,

    2024年01月21日
    浏览(33)
  • python VTK PyQt5 VTK环境搭建 创建 渲染窗口及三维模型,包含 三维模型交互;

      目录 Part1. VTK 介绍 Part2. PyQt5 VTK环境搭建 安装Anaconda 自带Python Anaconda下载 安装PyQt5 安装 VTK Part3 :PyQt VTK 结合样例: Part1. VTK 介绍 VTK(visualization toolkit)是一个开源的免费软件系统,主要用于三维计算机图形学、图像处理和可视化。Vtk 是在面向对象原理的基础上设计和实现的

    2024年02月11日
    浏览(38)
  • pyqt5窗口图标和背景的设置方法

    pyqt5窗口图标和背景的设置方法 一、PyQt5设置窗口图标的方法: 1.导入PyQt5.QtGui下的QIcon模块        from PyQt5.QtGui import QIcon 2.添加窗口的WindowIcon属性        Form.setWindowIcon(QIcon(\\\'./imge/azc.ico\\\')) 二、PyQt5设置窗口背景的方法: 第一种方法:使用窗口的StyleSheet属性方法(注意选择

    2024年02月04日
    浏览(34)
  • PyQt5:窗口大小根据屏幕大小自适应调整

     

    2024年02月12日
    浏览(41)
  • pyqt5设置标题栏三个按钮以及窗口大小

    组件也会受影响,范围0-1,0是全透明,1是不透明

    2024年02月13日
    浏览(37)
  • PyQt5 框架搭建+实战(多窗口打开,文件对话框)

    1.Qt设计师界面创建主窗口 2.转化成py文件 3.建立一个主窗口类,继承Qwidget和Qt设计师生成的UI类 4.写一个main函数入口,创建app,创建主窗口类实例,show(), app.exec() 我们不要在Qt设计师生成的界面上去增加我们的代码,因为这个界面我们一直都需要修改,修改后生成新的py代码

    2024年02月02日
    浏览(48)
  • python、pyqt5实现人脸检测、性别和年龄预测

    摘要:这篇博文介绍基于opencv:DNN模块自带的残差网络的人脸、性别、年龄识别系统,系统程序由OpenCv, PyQt5的库实现。如图系统可通过摄像头获取实时画面并识别其中的人脸表情,也可以通过读取图片识别,本文提供完整的程序文件并详细介绍其实现过程。博文要点如下:

    2024年02月07日
    浏览(82)
  • 【pyqt5界面化工具开发-8】窗口开发-QDialog对话框

    目录 一、调用父类的菜单 二、添加更多的布局在对话框内 和前面Qwedget一样的结构(不做过多介绍) 可以参考代码中的注释 这和前面讲的Qwedget窗口布局基本上一样了 运行结果:

    2024年02月11日
    浏览(35)
  • pyqt5, 如何在窗口上显示10个点地循环进度条。

    要在PyQt5窗口上显示从1个点逐渐增加到10个点,然后周而复始地循环,可以使用PyQt5的图形绘制功能和定时器来实现。以下是一个简单的例子: import sys from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtGui import QPainter, QColor, QBrush from PyQt5.QtCore import Qt, QTimer class PointDisplay(QWidget

    2024年02月14日
    浏览(24)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包