WaitForMultipleObjects和Event配合使用,限制程序运行一个实例

a.WaitForMultipleObjects:四个参数1。等待内核对象的数目;2。内核对象数组;3。bool类型t为等待数组里面所有的,f为等待数组当中的一个就行,有一个有信号就返回;4。等待Timeout的ms值。

b.CreateEvent:四个参数1。安全选项一般可设为nil;2。是否手动置信号,t在调用waitfor...后内核对象信号状态不变,需用SetEvent/ReSetEvent手动设置,f时waitfor后内核对象变为信号状态;3。设置信号的初始状态,t为有信息f反之;4。可以给内核对象一个名字,也可以设置为nil,当使用到程序限定只有一个运行的时候可以设定名字,这样当已经有相同名字的内核对象存在的时候,就会返回信息ERROR_ALREADY_EXISTS。

c.SetEvent:设为有信号状态。

d.ReSetEvent设为无信号状态。

以上个人理解,具体见MSDN

代码
var
Form1: TForm1;
FEvent:
array [1..2] of THandle;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
FEvent[
1] := CreateEvent(nil, true, false, nil);
FEvent[
2] := CreateEvent(nil, true, true, nil);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
r: DWORD;
begin
r :
= WaitForMultipleObjects(2,PWOHandleArray(@FEvent[1]),true,5000);
case r of
WAIT_OBJECT_
0: MessageDlg('OK1 WAIT_OBJECT_0',mtInformation,[mbOK],0);
WAIT_FAILED: MessageDlg(
'OK2 WAIT_FAILED' ,mtInformation,[mbOK],0);
WAIT_TIMEOUT: MessageDlg(
'OK3 WAIT_TIMEOUT' ,mtInformation,[mbOK],0);
end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
SetEvent(FEvent[
1]);
SetEvent(FEvent[
2]);
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
CloseHandle(FEvent[
1]);
CloseHandle(FEvent[
2]);
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
ReSetEvent(FEvent[
1]);
ReSetEvent(FEvent[
2]);
end;
限制程序运行一个实例:

代码
program Mutex;

uses
Forms,
Windows,
SysUtils,
unitMain
in 'unitMain.pas' {Form1};

{$R *.res}

var
hMutex: HWND;

begin
//hMutex := CreateMutex(nil,True,'MingTest');
hMutex :
= CreateEvent(nil,False,False,'MingTest');
//MessageBox(0,'Mutex has created!','Mutex!',0);
//if hMutex = 0 then //仅CreateMutex用此法可行
if GetLastError = ERROR_ALREADY_EXISTS then
begin
MessageBox(
0,'This program has executed!','Error!',0);
Exit;
end;
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.

原文地址:https://www.cnblogs.com/Jekhn/p/1915772.html