1

我有一个应用程序,它在主窗体的 OnCreate 期间检查应用程序的另一个实例是否已经通过创建互斥锁运行。如果是,则第二个实例将消息传递给第一个实例,然后自行关闭。它工作正常,除了第二个应用程序在关闭之前在屏幕上短暂闪烁其主窗体的一个小问题。

我有一个丑陋的技巧,即在主窗体 WindowState 设置为 wsMinimize 的情况下启动应用程序,然后使用具有 1 毫秒延迟的计时器来最大化窗体。但这似乎是一个可怕的黑客攻击。

有更好的想法吗?

procedure TMyAwesomeForm.FormCreate(Sender: TObject);
var
  h: HWND;
begin
  // Try to create mutex
  if CreateMutex(nil, True, '6EACD0BF-F3E0-44D9-91E7-47467B5A2B6A') = 0 then
    RaiseLastOSError;

  // If application already running
  if GetLastError = ERROR_ALREADY_EXISTS then 
  begin 
    // Prevent this instance from being the receipient of it's own message by changing form name
    MyAwesomeForm.Name := 'KillMe';

    // If this instance was started with parameters:   
    if ParamCount > 0 then 
    begin
      h := FindWindow(nil, 'MyAwesomeForm');

      //Pass the parameter to original application
      SendMessage(h, WM_MY_MESSAGE, strtoint(ParamStr(1)),0); 
    end;

    // Shut this instance down - there can be only one
    Application.Terminate; 
  end;

  // Create Jump Lists     
  JumpList := TJumpList.Create;  
  JumpList.ApplicationId := 'TaskbarDemo.Unique.Id';
  JumpList.DeleteList;
  CreateJList();
end;
4

1 回答 1

4

不要在表单类中执行检查,因为表单已创建它会显示。

恕我直言,执行像您这样的检查的更好地方是 .dpr 文件本身。

例如:

program Project3;

uses
  Forms,
  Windows, //<--- new citizens here
  SysUtils,
  Messages,
  Unit1 in 'Unit1.pas' {Form1};

{$R *.res}

function IsAlreadyRunning: Boolean;
var
  h: HWND;
begin
  //no comments, sorry, but I don't use comments to explain what the 
  //code explains by itself.
  Result := False;

  if CreateMutex(nil, True, '6EACD0BF-F3E0-44D9-91E7-47467B5A2B6A') = 0 then
    RaiseLastOSError;

  if GetLastError = ERROR_ALREADY_EXISTS then
  begin
    if ParamCount > 0 then
    begin
      h := FindWindow(nil, 'MyAwesomeForm');
      if h <> 0 then
        PostMessage(h, WM_MY_MESSAGE, strtoint(ParamStr(1)),0);
      Result := True;
    end;
  end;
end;

begin
  if not IsAlreadyRunning then
  begin
    Application.Initialize;
    Application.MainFormOnTaskbar := True;
    Application.CreateForm(TForm1, Form1);
    Application.Run;
  end;
end.
于 2013-03-02T01:17:39.123 回答