Minimise Delphi Application to System Tray

A short code snippet which will allow a program icon to be displayed in the application to system tray when the form is minimised.

By Tim Trott | Legacy Code | December 5, 2004
pascal
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ShellApi;

const
  WM_NOTIFYICON  = WM_USER+333;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
    tnid: TNotifyIconData;
    HMainIcon: HICON;
    procedure CMClickIcon(var msg: TMessage); message WM_NOTIFYICON;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.CMClickIcon(var msg: TMessage);
begin
  case msg.lparam of
    WM_LBUTTONDBLCLK : Show;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
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               := 'POP3 Server';

  Shell_NotifyIcon(NIM_ADD, @tnid);
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caNone;
  Hide;
end;

/If desired, you can tell Delphi not to show the mainform by adding to the
/'Project source' the line
/  Application.ShowMainForm := False;

/(Credits for this go to Peter Remeijer)

end.

Results

Program icon will be displayed in the System Tray when the form closes.

Explanation

Notice that this will prevent the form from being closed. The Hide procedure will remove the window, but the form is still present and now accessible through the icon in the system tray.

Notes

Although this code will allow you to place your applications main icon in the system tray and not in the start bar, there are several very good components available to do this for you. They also encapsulate many associated routines. See the VCL listings on Delphi32.com for tray icons.

Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

We respect your privacy, and will not make your email public. Learn how your comment data is processed.