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
请确保在使用互斥体名称时,使用全局唯一的名称,以避免与其他应用程序冲突。