萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 單實例應用實現:win32ui 互斥體與 wxPython 窗口激活

單實例模式核心邏輯

  1. 啟動時檢查是否已有實例運行
  2. 若存在:激活現有窗口並退出新實例
  3. 若不存在:正常啟動主窗口

Windows 原生方案:win32ui FindWindow


import win32ui
import win32con
import wx

def run_single_instance(window_title: str, create_main_window_func):
    """
    :param window_title: 窗口標題 (精確匹配)
    :param create_main_window_func: 創建主窗口的可調用對象
    """
    try:
        # 嘗試查找現有窗口
        existing = win32ui.FindWindow(None, window_title)
        if existing:
            # 窗口存在:恢復顯示並置頂
            existing.ShowWindow(win32con.SW_SHOWNORMAL)
            existing.SetForegroundWindow()
            print(f"Instance already running: '{window_title}'")
            return False  # 不創建新實例
    except win32ui.error:
        # 未找到窗口 (拋出異常)
        pass
    
    # 創建新實例
    app = wx.App()
    frame = create_main_window_func()
    frame.Show()
    app.MainLoop()
    return True

# 使用示例
if __name__ == '__main__':
    def create_frame():
        frame = wx.Frame(None, title="My Single Instance App", size=(800, 600))
        return frame
    
    run_single_instance("My Single Instance App", create_frame)

進階:互斥體方案 (更可靠,不依賴窗口標題)


import win32event
import win32api
import winerror
import sys
import wx

class SingleInstance:
    def __init__(self, mutex_name: str):
        self.mutex_name = mutex_name
        self.mutex = None
        self.created_new = False
    
    def __enter__(self):
        try:
            # 創建命名互斥體
            self.mutex = win32event.CreateMutex(None, False, self.mutex_name)
            last_error = win32api.GetLastError()
            
            if last_error == winerror.ERROR_ALREADY_EXISTS:
                # 已有實例運行
                self.created_new = False
                self._activate_existing()
                return False
            else:
                self.created_new = True
                return True
        except Exception as e:
            print(f"Mutex creation failed: {e}")
            return True  # 保守策略:允許運行
    
    def _activate_existing(self):
        """嘗試激活現有窗口 (需約定窗口標題或用其他 IPC)"""
        try:
            import win32gui
            # 廣播自定義消息通知現有實例激活
            HWND_BROADCAST = 0xFFFF
            WM_ACTIVATE_INSTANCE = win32gui.RegisterWindowMessage("WM_ACTIVATE_INSTANCE")
            win32gui.PostMessage(HWND_BROADCAST, WM_ACTIVATE_INSTANCE, 0, 0)
        except:
            pass
    
    def __exit__(self, *args):
        if self.mutex:
            win32api.CloseHandle(self.mutex)

# 使用
if __name__ == '__main__':
    with SingleInstance("Global\\MyApp_Singleton_Mutex") as instance:
        if not instance:
            sys.exit(0)  # 已有實例,退出
        
        app = wx.App()
        frame = wx.Frame(None, title="My App")
        frame.Show()
        app.MainLoop()

跨平台方案:文件鎖 (fcntl/msvcrt)


import sys
import os
import tempfile

class FileLockSingleInstance:
    def __init__(self, app_name: str):
        self.lock_file = os.path.join(tempfile.gettempdir(), f"{app_name}.lock")
        self.fp = None
    
    def acquire(self) -> bool:
        try:
            self.fp = open(self.lock_file, 'w')
            if sys.platform == 'win32':
                import msvcrt
                msvcrt.locking(self.fp.fileno(), msvcrt.LK_NBLCK, 1)
            else:
                import fcntl
                fcntl.flock(self.fp.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            
            self.fp.write(str(os.getpid()))
            self.fp.flush()
            return True
        except (IOError, OSError):
            if self.fp:
                self.fp.close()
            return False
    
    def release(self):
        if self.fp:
            try:
                if sys.platform == 'win32':
                    import msvcrt
                    msvcrt.locking(self.fp.fileno(), msvcrt.LK_UNLCK, 1)
                else:
                    import fcntl
                    fcntl.flock(self.fp.fileno(), fcntl.LOCK_UN)
            finally:
                self.fp.close()
                try:
                    os.unlink(self.lock_file)
                except:
                    pass

# 使用
if __name__ == '__main__':
    lock = FileLockSingleInstance("my_awesome_app")
    if not lock.acquire():
        print("Another instance is running")
        sys.exit(0)
    
    try:
        # 運行主程序
        import wx
        app = wx.App()
        wx.Frame(None, title="Cross-platform Single Instance").Show()
        app.MainLoop()
    finally:
        lock.release()

wxPython 專用:SingleInstanceChecker


import wx

def run_wx_single_instance(app_name: str, main_frame_factory):
    # 檢查實例
    checker = wx.SingleInstanceChecker(app_name)
    if checker.IsAnotherRunning():
        wx.MessageBox(f"'{app_name}' is already running!", "Warning", wx.OK | wx.ICON_WARNING)
        return False
    
    # 正常啟動
    app = wx.App()
    frame = main_frame_factory()
    frame.Show()
    app.MainLoop()
    return True

if __name__ == '__main__':
    run_wx_single_instance("MyWxApp-{UID}", lambda: wx.Frame(None, title="Hello"))

wx.SingleInstanceChecker 內部使用文件鎖,跨平台、無額外依賴,wxPython 項目首選。

方案選型指南

方案平台可靠性依賴推薦場景
wx.SingleInstanceChecker跨平台高wxPythonwxPython 專用
命名互斥體Windows高pywin32Windows 原生/C++ 互操作
文件鎖跨平台中標準庫無 GUI 框架、腳本、服務
FindWindowWindows低pywin32快速原型、窗口標題固定

選擇合適的單實例機制,避免資源衝突、數據損壞與用戶困惑,是桌面應用專業度的體現。

copyright © 萬盛學電腦網 all rights reserved