首先在项目文件(*.dpr)的uses段中添加Windows的引用,然后声明一个hWnd类型的变量hMutex:
var
hMutex:hWnd;
最后在项目文件的begin和end中添加以下代码:
Application.Initialize;
Application.Title:='test';
CreateMutex(nil,false,'test');
if GetLastError<>Error_Already_Exists then
begin
Application.CreateForm(TForm1, Form1);
Application.Run;
end
else
begin
Application.MessageBox('本程序只允许同时运行一个','Error');
end;
Application对象的Title属性的值可以根据自己的需要设置。通过CreateMutex函数来创建一个互斥量,如果GetLastError不等于Error_Already_Exists,也就是本程序的实例没有运行,那么就正常启动程序,反之则表示本程序的实例已经在运行,那么就会弹出一个对话框提示用户,不启动程序。