如何阻止一程序运行多个实例(0分)

M

maxwel

Unregistered / Unconfirmed
GUEST, unregistred user!
如何阻止一程序运行多个实例
 
if FindWindow(nil,'aaaaaa')=0 then
begin
Application.Initialize;
Application.Title := 'aaaaaa;
Application.CreateForm(TProgress_DM, Progress_DM);
Application.CreateForm(TMain_Form, Main_Form);
Application.CreateForm(TContract_Form, Contract_Form);
Application.CreateForm(TRightHandover_Form, RightHandover_Form);
Application.CreateForm(TGeo_Code_Form, Geo_Code_Form);
Application.CreateForm(TScaleForm, ScaleForm);
Application.Run;
end
else
begin
ShowMessage('一个程序的实例已经运行!');
end;
 
用aplication.createform()或tform.create()
判断有没有相同的事例存在
begin
if not assiged(someform) then
try
someform.showmodal;
finally
someform.free;
someform:=nil;
end ;
end
else
someform.showmodal;
end;
 
FUNCTION FkAppIsLoad(vIdent:STRING):BOOL;
BEGIN
CreateMutex(Nil,FALSE,PANSICHAR(vIdent));
Result:=getlasterror=error_already_exists;
END;
vIdent是你的程序的识别码。这是最好的办法!
 
上边的,请问可不可以详细些,要入到什么地方,Result:=getlasterror=error_already_exists;是否有错,谢谢
 
[8D]没有错误,就这样!
加载在 主程序的 Application.Initialize;后即可[:D]
 
[:D][:D]别忘了Uses Windows。
 
//需要声明的变量
var
mHandle: THandle;
PreviousInstanceWindow:HWND;
Project: string;
AppName:string;
//在主窗体的pas文件最后一个end前增加如下代码:
initialization
Project := 'mzsf'; //此处可以自己定义一个标志
mHandle := CreateMutex(nil, True, PChar(Project));
if GetLastError = ERROR_ALREADY_EXISTS then
begin
AppName:=Application.Title;
Application.ShowMainForm := false;
Application.Title := 'destroy me';
PreviousInstanceWindow := FindWindow(nil,pchar(AppName));
if PreviousInstanceWindow <> 0 then
if IsIconic(PreviousInstanceWindow) then
ShowWindow(PreviousInstanceWindow,SW_RESTORE)
else
SetForegroundWindow(PreviousInstanceWindow);
Application.Terminate;
end;
finalization
if mHandle <> 0 then
CloseHandle(mHandle);


此段代码为《delphi案例教程》中发现的,与大家共享
 
顶部