import ctypes
import sys
def is_program_running():
??? # 創建互斥體
??? mutex_name = "Global\\MonitorClientMutex"
??? h_mutex = ctypes.windll.kernel32.CreateMutexW(None, False, mutex_name)
??? # 檢查互斥體是否已經存在
??? if ctypes.windll.kernel32.GetLastError() == 183:? # ERROR_ALREADY_EXISTS
??????? print("程序已經在運行.")
??????? return True
??? return False
if __name__ == "__main__":
??? if is_program_running():
??????? ctypes.windll.user32.MessageBoxTimeoutW(
??????????? None, "程序已經運行.....", "警告", 0x40 | 0x1, 0, 1000
??????? )
??????? sys.exit(0)
??? # 在這里執行你的應用程序代碼
??? print("程序啟動中...")
??? # Your application code here
請確保在使用互斥體名稱時,使用全局唯一的名稱,以避免與其他應用程序沖突。