Search code examples
windowsdelphifiremonkeydelphi-xe8

Capture Minimize event for Firemonkey form?


I'm trying to do a very simple task... Detect when my form has been minimized. But it seems Firemonkey has absolutely no way of handling this. I've tried to use AllocateHWnd to intercept WM_SYSCOMMAND messages, but all I get is WM_ACTIVATEAPP messages and nothing else.

CreateForm:

AllocateHWnd(WndProcHandler);

WndProcHandler:

procedure TfrmMain.WndProcHandler(var Message: TMessage);
begin
  if Message.msg = WM_SYSCOMMAND then
    OutputDebugStringA('got command');
end;

Solution

  • Got it working with the following code. Looks for the WM_SIZE command and SIZE_MINIMIZED parameter to detect all minimising events.

    uses
      Winapi.Windows, Winapi.Messages;
    
    var
      WndProcHook: THandle;
    
    function WndProc(Code: integer; WParam, LParam: LongInt): LRESULT; stdcall;
    var
      msg: TCWPRetStruct;
    begin;
      if (Code >= HC_ACTION) and (LParam > 0) then begin
        msg := PCWPRetStruct(LParam)^;
        if (msg.Message = WM_SIZE) and (msg.WParam = SIZE_MINIMIZED) then begin
          // Application has been minimized
          // Check msg.wnd = WindowHandleToPlatform(Form1.Handle).wnd if necessary
        end;
      end;
      result := CallNextHookEx(WndProcHook, Code, WParam, LParam)
    end;
    
    initialization
      WndProcHook := SetWindowsHookEx(WH_CALLWNDPROCRET, @WndProc, 0, GetCurrentThreadId);
    
    finalization
      UnhookWindowsHookEx(WndProcHook);