Title: System Tray Example
Question: This source code is an example of how to have a delphi application run as an icon in the system tray. When the application is minimized it closes to the icon instead of a button on the task bar.
Answer:
--------------------------------
Delphi Project file
--------------------------------
program SystemTray;
{
System Tray Example
Author: Ryan Brown
Ryan4416@yahoo.com
Program Description: A simple example of how to get a
delphi application to appear as an icon in the
system tray.
License: Free
}
uses
Forms,
Controls,
Dialogs,
ShellApi,
Windows,
frmMainUnt in 'frmMainUnt.pas' {frmMain};
{$R *.RES}
var
NotifyIconData : TNotifyIconData;
begin
Application.Initialize;
Application.ShowMainForm := False;
Application.CreateForm(TfrmMain, frmMain);
NotifyIconData.cbSize := SizeOf( NotifyIconData );
NotifyIconData.Wnd := frmMain.Handle;
NotifyIconData.uCallbackMessage := WM_ShellIcon;
NotifyIconData.hIcon := Application.Icon.Handle;
NotifyIconData.szTip := 'System Tray Example';
NotifyIconData.uFlags := NIF_TIP + NIF_MESSAGE + NIF_ICON;
try
Shell_NotifyIcon( NIM_ADD, @NotifyIconData );
ShowWindow(Application.Handle, SW_HIDE);
Application.Run;
finally
Shell_NotifyIcon( NIM_DELETE, @NotifyIconData );
end;
end.
--------------------------------
Main Form File
--------------------------------
unit frmMainUnt;
{
System Tray Example
Author: Ryan Brown
Ryan4416@yahoo.com
Program Description: A simple example of how to get a
delphi application to appear as an icon in the
system tray.
License: Free
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus;
const
WM_ShellIcon = WM_USER + 1;
type
TfrmMain = class(TForm)
mnuIconTray: TPopupMenu;
mniViewProgram: TMenuItem;
mniExitProgram: TMenuItem;
procedure FormActivate(Sender: TObject);
procedure mniExitProgramClick(Sender: TObject);
procedure mniViewProgramClick(Sender: TObject);
private
{ Private declarations }
procedure ShellIcon( var Msg : TMessage ); message WM_ShellIcon;
procedure OnMinimize( var Msg : TWMSysCommand ); message WM_SYSCOMMAND;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.DFM}
{ TfrmMain }
procedure TfrmMain.ShellIcon(var Msg: TMessage);
var
Point : TPoint;
begin
case Msg.LParam of
WM_LBUTTONDBLCLK : begin
Show;
SetForegroundWindow( Handle );
end;
WM_RBUTTONUP : begin
SetForegroundWindow( Handle );
GetCursorPos( Point );
mnuIconTray.Popup( Point.x, Point.y );
PostMessage( Handle, WM_USER, 0, 0 );
end;
end;
end;
procedure TfrmMain.FormActivate(Sender: TObject);
begin
ShowWindow(Application.Handle, SW_HIDE);
end;
procedure TfrmMain.mniExitProgramClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TfrmMain.OnMinimize(var Msg: TWMSysCommand);
begin
if( Msg.CmdType = SC_MINIMIZE ) or
( Msg.CmdType = SC_CLOSE ) then
Hide
else
inherited;
end;
procedure TfrmMain.mniViewProgramClick(Sender: TObject);
begin
Show;
SetForegroundWindow( Handle );
end;
end.