在做Delphi的一个小工具的时候,要让自己的程序保证只启动一个实例如下有几种方法实现:
1.使用系统函数FindWindows()函数来实现:
program Project1; uses Forms, Windows,//添加Windows单元 offertool in 'offertool.pas' {foffertool}, MyThread in 'MyThread.pas', offerchild in 'offerchild.pas' {fofferchild}; {$R *.res} var Hwnd:THandle; //添加一个句柄 begin Hwnd := FindWindow('Tfoffertool',nil); //参数1:窗口类名,参数2:窗口标题 if Hwnd=0 then begin Application.Initialize; Application.CreateForm(Tfoffertool, foffertool); Application.Run; end else begin Application.MessageBox('已经运行了一个实例','提示',MB_OK); end; end.
2.使用使用互斥对象来实现:
program Project1; uses Forms, Windows, //添加Windows单元 offertool in 'offertool.pas' {foffertool}, MyThread in 'MyThread.pas', offerchild in 'offerchild.pas' {fofferchild}; {$R *.res} var myMutex:THandle; //添加一个互斥锁句柄 begin myMutex := CreateMutex(nil,True,'新股代理申购报盘'); if GetLastError<>ERROR_ALREADY_EXISTS then begin Application.Initialize; Application.CreateForm(Tfoffertool, foffertool); Application.Run; end else Application.MessageBox('已经运行了一个实例','提示',MB_OK); end.