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()
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()
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 | 跨平台 | 高 | wxPython | wxPython 專用 |
| 命名互斥體 | Windows | 高 | pywin32 | Windows 原生/C++ 互操作 |
| 文件鎖 | 跨平台 | 中 | 標準庫 | 無 GUI 框架、腳本、服務 |
| FindWindow | Windows | 低 | pywin32 | 快速原型、窗口標題固定 |
選擇合適的單實例機制,避免資源衝突、數據損壞與用戶困惑,是桌面應用專業度的體現。