Delphi - 互斥对象下实现系统的单例模式

使用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;
    //*****************************单例模式********************************

猜你喜欢

转载自www.cnblogs.com/jeremywucnblog/p/11450919.html
今日推荐