关于禁止程序重复启动的另一种需要与实现《转》
程序需要禁止重复启动, 但需要保留新的、关闭旧的.
=================================================
从主窗口的类名下手吧; 写了一个函数, 在 OnCreate 中调用即可:
1 { 函数 } 2 procedure CloseSameClassNameWindow(ACurrentWindow: HWND; const AClassName: string); 3 var 4 h: HWND; 5 buf: array[0..255] of Char; 6 begin 7 h := ACurrentWindow; 8 while h > 0 do 9 begin 10 h := GetWindow(h, GW_HWNDNEXT); 11 GetClassName(h, buf, Length(buf)); 12 if buf = AClassName then 13 begin 14 SendMessage(h, WM_CLOSE, 0, 0); 15 Break; 16 end; 17 end; 18 end; 19 20 { 调用 } 21 procedure TForm1.FormCreate(Sender: TObject); 22 begin 23 CloseSameClassNameWindow(Handle, ClassName); 24 end;
=====================================================
从程序文件中控制更简单, 一句话:
1 program Project1; 2 3 uses 4 Forms, Windows, Messages, 5 Unit1 in 'Unit1.pas' {Form1}; 6 7 {$R *.res} 8 9 begin 10 Application.Initialize; 11 SendMessage(FindWindow('TForm1', nil), WM_CLOSE, 0, 0); //假如主窗体的类名是 TForm1 12 Application.MainFormOnTaskbar := True; 13 Application.CreateForm(TForm1, Form1); 14 Application.Run; 15 end.