手頭的程序需要禁止重復(fù)啟動, 但需要保留新的、關(guān)閉舊的.
我想還是從主窗口的類名下手吧; 寫了一個函數(shù), 在 OnCreate 中調(diào)用即可:
{ 函數(shù) }
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;
{ 調(diào)用 }
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.