1. 看到网上有人做硬件显示的COM口。作为资深软件开发人员,觉得这点小事情,还要掏Money来实现,有点太LOW了。
2. 直接用Python代码实现,放在启动里面,插入或者移除USB的串口,都能够正确提示。
3. 闲话少说,直接上代码。
import sys,os
from PyQt5.QtWidgets import QApplication, QSystemTrayIcon, QMenu, QAction, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtCore import QTimer
import serial.tools.list_ports
class USBMonitorThread(QThread):
device_connected = pyqtSignal(str)
device_disconnected = pyqtSignal(str)
def run(self):
prev_ports = set(serial.tools.list_ports.comports())
while True:
current_ports = set(serial.tools.list_ports.comports())
new_ports = current_ports - prev_ports
removed_ports = prev_ports - current_ports
for port in new_ports:
self.device_connected.emit(port.device)
for port in removed_ports:
self.device_disconnected.emit(port.device)
prev_ports = current_ports
self.msleep(1000) # 每秒检查一次
class SystemTrayIcon(QSystemTrayIcon):
def __init__(self, icon, parent=None):
super(SystemTrayIcon, self).__init__(icon, parent)
self.setToolTip("USB Monitor")
self.create_menu()
self.USB_thread = USBMonitorThread()
self.USB_thread.device_connected.connect(self.show_connected_notification)
self.USB_thread.device_disconnected.connect(self.show_disconnected_notification)
self.USB_thread.start()
def create_menu(self):
menu = QMenu()
exitAction = QAction("退出", self)
exitAction.triggered.connect(sys.exit)
menu.addAction(exitAction)
self.setContextMenu(menu)
def show_connected_notification(self, port_name):
message = f"新USB设备已连接: {port_name}"
self.show_notification_message(message)
def show_disconnected_notification(self, port_name):
message = f"USB设备已移除: {port_name}"
self.show_notification_message(message)
def show_notification_message(self, message, timeout=5000): # 假设5秒后关闭
msg_box = QMessageBox(QMessageBox.Information, "USB设备通知", message)
timer = QTimer()
timer.singleShot(timeout, msg_box.close) # 在timeout毫秒后关闭消息框
msg_box.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
# icon = QIcon("3GP.ico") # 替换为你的ICO文件路径
tray_icon = SystemTrayIcon(QIcon('app3_icon.ico'))
tray_icon.show()
while True: # 添加无限循环
app.exec_()
\n#技术交流#

登录 或 注册 后才可以进行评论哦!
还没有评论,抢个沙发!