title: Delphi: Minimize application to systray
body: <p>I want to minimize a Delphi application to the systray instead of the task bar.</p>
  
  <p>The necessary steps seem to be the following:</p>
  
  <ol>
  <li>Create icon which should then be displayed in the systray.</li>
  <li>When the user clicks the [-] to minimize the application, do the following:
  
  <ol>
  <li>Hide the form.</li>
  <li>Add the icon (step #1) to the systray.</li>
  <li>Hide/delete the application's entry in the task bar.</li>
  </ol></li>
  <li>When the user double-clicks the application's icon in the systray, do the following:
  
  <ol>
  <li>Show the form.</li>
  <li>Un-minimize the application again and bring it to the front.</li>
  <li>If "WindowState" is "WS_Minimized" set to "WS_Normal".</li>
  <li>Hide/delete the application's icon in the systray.</li>
  </ol></li>
  <li>When the user terminates the application, do the following:
  
  <ol>
  <li>Hide/delete the application's icon in the systray.</li>
  </ol></li>
  </ol>
  
  <p>That's it. Right?</p>
  
  <p>How could one implement this in Delphi?</p>
  
  <p>I've found the following code but I don't know why it works. It doesn't follow my steps described above ...</p>
  
  <pre><code>unit uMinimizeToTray;
  
  interface
  
  uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
    Dialogs, StdCtrls, ShellApi;
  
  const WM_NOTIFYICON = WM_USER+333; 
  
  type
    TMinimizeToTray = class(TForm)
      procedure FormCreate(Sender: TObject);
      procedure FormClose(Sender: TObject; var Action: TCloseAction);
      procedure CMClickIcon(var msg: TMessage); message WM_NOTIFYICON;
    private
      { Private-Deklarationen }
    public
      { Public-Deklarationen }
    end;
  
  var
    MinimizeToTray: TMinimizeToTray;
  
  implementation
  
  {$R *.dfm}
  
  procedure TMinimizeToTray.CMClickIcon(var msg: TMessage);
  begin
    if msg.lparam = WM_LBUTTONDBLCLK then Show;
  end;
  
  procedure TMinimizeToTray.FormCreate(Sender: TObject);
  VAR tnid: TNotifyIconData;
      HMainIcon: HICON;
  begin
    HMainIcon := LoadIcon(MainInstance, 'MAINICON');
    Shell_NotifyIcon(NIM_DELETE, @tnid);
    tnid.cbSize := sizeof(TNotifyIconData);
    tnid.Wnd := handle;
    tnid.uID := 123;
    tnid.uFlags := NIF_MESSAGE or NIF_ICON or NIF_TIP;
    tnid.uCallbackMessage := WM_NOTIFYICON;
    tnid.hIcon := HMainIcon;
    tnid.szTip := 'Tooltip';
    Shell_NotifyIcon(NIM_ADD, @tnid);
  end;
  
  procedure TMinimizeToTray.FormClose(Sender: TObject; var Action: TCloseAction);
  begin
    Action := caNone;
    Hide;
  end;
  
  end.
  </code></pre>