几乎立即关闭第二个应用程序实例时,停止在屏幕上短暂闪烁

时间:2013-03-02 01:02:19

标签: delphi delphi-xe3

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

我有一个丑陋的黑客启动应用程序,主窗体WindowState设置为wsMinimize,然后使用延迟1ms的计时器来最大化窗体。但这似乎是一个可怕的黑客。

有更好的想法吗?

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;

1 个答案:

答案 0 :(得分: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.