方法一:搜索主窗口的一个副本
program Project1;
uses
Forms,
main in 'main.pas' {Form1},
windows;
{$R *.res}
var
Hwnd:THandle;
begin
Hwnd :=FindWindow('TForm1',nil);
if Hwnd = 0 then
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end
else
begin
if not IsWindowVisible(FoundWnd) then
PostMessage(FoundWnd,wm_App,0,0);
SetForegroundWindow(Hwnd);
end;
end.
unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TForm1 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
procedure WMApp(var msg:TMessage);message wm_App;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.WMApp(var msg:TMessage);
begin
Application.Restore; //恢复一个最小化的应用程序到正常大小。
end;
end.
缺点:如果在Delphi IDE中有一个窗体也为TForm1,则此程序不会启动,同样,在delphi中运行此程序也不会启动程序。另外,还有可能其他应用程序也有相同的主窗体名称。
方法二:使用互斥对象
program Project2;
uses
Forms,
main1 in 'main1.pas' {Form1},
Windows;
{$R *.res}
var
hMutex:THandle;
begin
HMutex :=CreateMutex(nil,false,'OneCopyMutex'); //创建一个互斥体
if waitForSingleObject(hMutex,0)<> wait_timeOut then
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end;
end.
缺点:如果运行两次该实例,将可以看到该程序会临时创建该应用程序的新拷贝(会在任务栏中出现它的图标),当规定时间后,再解除它。