Learning never exhausts the mind

By

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.

 

Enjoyed this post? Why not share it!

If you enjoyed this post, please share it with others. Click one of the social media buttons below to share on Facebook, Twitter, LinkedIn, Pinterest or email to a friend.

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.