delphi只运行一个实例(源码)

program web2003;//实例一

uses
Windows,
Forms,
web_main in 'web_main.pas' {FrmMain};
{$R *.res}

var
AppHandle: THandle;
begin
Application.Initialize;
AppHandle:=CreateMutex(nil,False,PChar('你自己定义的名称'));
if AppHandle=0 then
begin
MessageBox(0,PChar('创建互斥对象失败'),PChar('错误'),MB_OK+MB_ICONINFORMATION);
exit;
end;
if (AppHandle<>0) and (GetLastError()=ERROR_ALREADY_EXISTS) then
begin
MessageBox(0,PChar('该程序已经在运行了'),PChar('温馨提示'),MB_OK+MB_ICONINFORMATION);
CloseHandle(AppHandle);
exit;
end;
Application.CreateForm(TFrmMain, FrmMain);
Application.Run;
CloseHandle(AppHandle);
end.


-------------------分隔线----都在工程源文件中实现 *.dpr------------
一 使用全局原子

program Project1;

uses
windows,
Forms,
Dialogs,
Unit1 in 'Unit1.pas' {Form1};

{$R *.res}

const
myatom='我的全局原子方法';
begin
if GlobalFindAtom(myatom)=0 then
begin
GlobalAddAtom(myatom);
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
GlobalDeleteAtom(GlobalFindAtom(myatom));
end
else
showmessage('已经有一个实例在运行');
end.



二 使用互斥对象

var
mymutex: THandle;
begin
mymutex:=CreateMutex(nil,True,'我的互斥对象');
if GetLastError<>ERROR_ALREADY_EXISTS then
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end
else
showmessage('已经有一个实例在运行');
end.



三 使用FindWindow函数

var
myhandle: THandle;
begin
myhandle:=FindWindow(nil,'Form1');
if myhandle=0 then
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end
else
showmessage('已经有一个实例在运行');
end.

相关主题
相关文档
最新文档