unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
mHandle: THandle;
// 保存Mutex句柄
PreviousInstanceWindow:HWND;
Project: string;
AppName:string;
implementation
{$R *.DFM}
initialization
Project := 'RunOnlyOnce_MyProject';
//此处定义自己的项目名称,作为要创建的互斥区名,最好有自己特点已防止重复
mHandle := CreateMutex(nil, True, PChar(Project));
// lpMutexAttributes设为nil,bInitialOwner设为True(即本程序拥有该互斥区)
if GetLastError = ERROR_ALREADY_EXISTS then
//该互斥区已存在则表明已有本程序的另一个实例在运行
begin
showmessage('已经有该程序的一个实例在运行');
AppName:=Application.Title;
//保存程序标题
Application.ShowMainForm := false;
//不显示本窗口
Application.Title := 'destroy me';
//改变程序标题,以使FindWindow找到的是前一个实例窗口
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);
end.