2005. április 20., szerda

Creating a system tray application


Problem/Question/Abstract:

How I can make my application not appear on the main display and but just in the system tray on startup?

Answer:

You could use RxLib (freeware component collection) - it contains a component that does this. Drop the RxTrayIcon component on your main form and minimize/ hide your application with this code:

ShowWindow(Application.Handle, SW_HIDE);
Application.Minimize;

If using RxLib is not an option, then you can build it yourself with the ShellAPI function Shell_NotifyIcon(). Use the application from below as a starting point.

  
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls,
  Forms, Dialogs, Menus, ShellAPI, ExtCtrls;

type
  TForm1 = class(TForm)
    PopupMenu1: TPopupMenu;
    Open1: TMenuItem;
    Exit1: TMenuItem;
    procedure FormCreate(Sender: TObject);
    procedure Open1Click(Sender: TObject);
    procedure Exit1Click(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { private declarations }
    procedure WndProc(var Msg: TMessage); override;
  public
    { public declarations }
    IconData: TNotifyIconData;
    IconCount: integer;
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.WndProc(var Msg: TMessage);
var
  aPoint: TPoint;
begin
  case Msg.Msg of
    WM_USER + 1:
      case Msg.lParam of
        WM_RBUTTONDOWN:
          begin
            SetForegroundWindow(Handle);
            GetCursorPos(aPoint);
            PopupMenu1.Popup(aPoint.x, aPoint.y);
            PostMessage(Handle, WM_NULL, 0, 0);
          end
      end;
  end;
  inherited;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  BorderIcons := [biSystemMenu];
  IconCount := 0;
  IconData.cbSize := sizeof(IconData);
  IconData.Wnd := Handle;
  IconData.uID := 100;
  IconData.uFlags := NIF_MESSAGE + NIF_ICON + NIF_TIP;
  IconData.uCallbackMessage := WM_USER + 1;
  IconData.hIcon := Application.Icon.Handle;
  StrPCopy(IconData.szTip, Application.Title);
  Shell_NotifyIcon(NIM_ADD, @IconData);
end;

procedure TForm1.Open1Click(Sender: TObject);
begin
  Form1.Show;
  ShowWindow(Application.Handle, SW_HIDE);
end;

procedure TForm1.Exit1Click(Sender: TObject);
begin
  Shell_NotifyIcon(NIM_DELETE, @IconData);
  Application.ProcessMessages;
  Application.Terminate;
end;

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

begin
  ShowWindow(Application.Handle, SW_HIDE);
end;

Nincsenek megjegyzések:

Megjegyzés küldése