手头的程序需要禁止重复启动, 但需要保留新的、关闭旧的.
我想还是从主窗口的类名下手吧; 写了一个函数, 在 OnCreate 中调用即可:
{ 函数 } procedure CloseSameClassNameWindow(ACurrentWindow: HWND; const AClassName: string); var h: HWND; buf: array[0..255] of Char; begin h := ACurrentWindow; while h > 0 do begin h := GetWindow(h, GW_HWNDNEXT); GetClassName(h, buf, Length(buf)); if buf = AClassName then begin SendMessage(h, WM_CLOSE, 0, 0); Break; end; end; end; { 调用 } procedure TForm1.FormCreate(Sender: TObject); begin CloseSameClassNameWindow(Handle, ClassName); end;
从程序文件中控制更简单, 一句话:
program Project1; uses Forms, Windows, Messages, Unit1 in 'Unit1.pas' {Form1}; {$R *.res} begin Application.Initialize; SendMessage(FindWindow('TForm1', nil), WM_CLOSE, 0, 0); //假如主窗体的类名是 TForm1 Application.MainFormOnTaskbar := True; Application.CreateForm(TForm1, Form1); Application.Run; end.