Web Design that taps into the haromny and vision of your dreams.

Minimise Delphi Application to System Tray

By on in Coding

284 words, estimated reading time 2 minutes.

Code snippet which will allow a program icon to be displayed in the system tray when the form is minimised.

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.

Last updated on: Saturday 24th June 2017

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.