本实例介绍如何做得同时只能够运行一个程序。
首先在项目文件(*.dpr)的uses段中添加Windows的引用,然后声明一个hWnd类型的变量hMutex:
项目文件(*.dpr)的内容如下:
图4-8 运行提示
有些系统服务不能够同时让用户多次运行,利用本程序提供的方法可以限定同时只能够运行一个程序。
首先在项目文件(*.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,也就是本程序的实例没有运行,那么就正常启动程序,反之则表示本程序的实例已经在运行,那么就会弹出一个对话框提示用户,不启动程序。项目文件(*.dpr)的内容如下:
program Project1;
uses
Forms, Windows,
Unit1 in 'Unit1.pas' {Form1};
{$R *.res}
var
hMutex:hWnd;
begin
Application.Initialize;
Application.Title:='test';
hMutex:=CreateMutex(nil,false,'test');
if GetLastError<>Error_Already_Exists then
begin
Application.CreateForm(TForm1, Form1);
Application.Run;
end
else
begin
Application.MessageBox('本程序只允许同时运行一个','Error');
ReleaseMutex(hMutex);
end;
end.
保存文件。如果同时多次运行本程序,就会弹出如图4-8所示的对话框。
图4-8 运行提示
有些系统服务不能够同时让用户多次运行,利用本程序提供的方法可以限定同时只能够运行一个程序。