使用 CreateMutex 函数创建互斥对象
利用 Windows 系统函数 CreateMutex(), 找出当前系统是否已经存在指定进程的实例, 如果没有则创建一个互斥体.
CreateMutex 函数原型如下:
- function CreateMutex(lpMutexAttributes: PSecurityAttributes; bInitialOwner: BOOL; lpName: PChar): THandle;
- function CreateMutex(lpMutexAttributes: PSecurityAttributes; bInitialOwner: BOOL; lpName: PChar): THandle;
其中参数:
lpMutexAttributes :SECURITY_ATTRIBUTES 结构类型指针, 可以为 NULL.
bInitialOwner : 是否初始化互斥体.
lpName : 互斥体对象的名称, 一般是工程的名称.
最终, 函数返回一个互斥体句柄.
Delphi WinFrm 利用互斥对象实现单例模式
单击 Project,View Source;
uses 中添加 Windows;
Begin 和 End 之间添加如下代码.
- //***************************** 单例模式 ********************************
- CreateMutex(nil, False, 'Application Name');
- if GetLastError = ERROR_ALREADY_EXISTS then
- begin
- Application.MessageBox('系统已经开启了, 请确认下!', '提示', MB_OK);
- Halt(0);
- end;
- //***************************** 单例模式 ********************************
来源: https://www.cnblogs.com/jeremywucnblog/p/11450919.html