下面的代码有问题吗?(10分)

Z

zqw0117

Unregistered / Unconfirmed
GUEST, unregistred user!
我想让我的程序只启动一次(保证内存中只有一个副本),下面是我的代码,请问有无
问题?

program WaitForSingleObject_app;

uses
Forms,
Windows,
Dialogs,
WaitForSingleObject_func in 'WaitForSingleObject_func.pas' {Form1};

{$R *.res}

begin
if WaitForSingleObject(CreateMutex(nil, False, 'MyProgramsMutexName'),0)<>WAIT_OBJECT_0 then
begin
Exit;
end;
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
 
用findWindows('窗体名')更好
 
FindWindow不好,因为执行时FindWindow会枚举所有窗口,如果程序多的话,会很慢的。
 
program pServer;

uses
Forms, Windows, Comserv, Sysutils,
uCover in 'uCover.pas' {frmCover},
main in 'main.pas' {FrmMain},

var
HMuTex:HWnd;
Ret:Integer;

{$R *.RES}

begin
//使程序只运行一次
HMuTex:=CreateMuTex(nil,false,Pchar(ExtractFilename(Application.ExeName)));
Ret:=GetLastError;
if Ret <> Error_Already_Exists then
begin
frmCover:= TfrmCover.Create(Application);
frmCover.Show; //显示启动封面
frmCover.Update;
Application.Initialize;
Application.CreateForm(TFrmMain, FrmMain);
frmCover.Hide;
frmCover.Destroy;
Application.Run;
end
else ReleaseMuTex(HMuTex);
end.
 
上面的代码好像仅仅创建了互斥对象,没有使用WaitForSingleObject函数,可以解释为什么吗?
 
不就是要做个大家都看得见的"记号"吗,创建互斥对象足矣!
 
不为什么,只要创建失败就是已经有副本在运行了
 
改成这样可以吗?

program WaitForSingleObject_app;

uses
Forms,
Windows,
Dialogs,
WaitForSingleObject_func in 'WaitForSingleObject_func.pas' {Form1};

var
HMuTex:HWnd;
Ret:Integer;
{$R *.res}

begin
//使程序只运行一次
HMuTex:=CreateMuTex(nil,false,'WaitForSingleObject_Exe');
Ret:=GetLastError;
if Ret = Error_Already_Exists then
begin
ReleaseMuTex(HMuTex);
CloseHandle(HMutex);
Exit;
end;
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
ReleaseMutex(HMutex);
CloseHandle(HMutex);
end.
 
没有人回答那么就结了吧。
 
顶部