其实这是比较简单的,只要我们知道Window的一些数据结构及相关的API函数就可以实现了。本人曾在VC及Delphi中都实现过这种程序,以下我的一些心得,希望对大家有借鉴作用。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
shellapi;
const
WM_MYNOTIFY = WM_USER + 1000 ;//消息
strNotifyTip=hello;//提示
ID_MAIN = 100 ; // 定义图标的ID
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Function AddIcon(hwnd : HWND):Boolean ;
Function RemoveIcon(hwnd:HWND):Boolean ;
Procedure MyNotify(var Msg:TMessage);message WM_MYNOTIFY;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
AddIcon(handle);
end;
//以下函数加入图标,可在程序初始化时加入。
Function TForm1.AddIcon(hwnd : HWND):Boolean ;
var
nid : NOTIFYICONDATA ;
begin
nid.cbSize := sizeof(NOTIFYICONDATA);
nid.Wnd := hwnd;
nid.uID := ID_MAIN;
nid.uFlags := NIF_MESSAGE or NIF_ICON or NIF_TIP;
nid.uCallbackMessage := WM_MYNOTIFY;
nid.hIcon := LoadIcon(hInstance,MAINICON);
strCopy(nid.szTip,strNotifyTip);
AddIcon := Shell_NotifyIcon(NIM_ADD, @nid);
end ;
Function TForm1.RemoveIcon(hwnd:HWND):Boolean ;
var
nid : NOTIFYICONDATA;
begin
nid.cbSize := sizeof(NOTIFYICONDATA);
nid.Wnd := hwnd;
nid.uID := ID_MAIN;
nid.uFlags := 0;
RemoveIcon := Shell_NotifyIcon(NIM_DELETE, @nid);
end ;
procedure TForm1.FormDestroy(Sender: TObject);
begin
RemoveIcon(handle);
end;
Procedure TForm1.MyNotify(var Msg:TMessage);
begin
case msg.LParam of
WM_LBUTTONDOWN : begin
Application.MessageBox(Left button click ,My Notify,MB_OK);
end;
end;
end;
end.
你还可以改变图标。代码如下:
nid.cbSize := sizeof(NOTIFYICONDATA);
nid.Wnd := hwnd;
nid.uID := ID_MAIN;
nid.uFlags := NIF_MESSAGE or NIF_ICON or NIF_TIP;
nid.uCallbackMessage := WM_TRAYNOTIFY;
nid.hIcon := 你的图标。
strCopy(nid.szTip,strNotifyTip);
Shell_NotifyIcon(NIM_MODIFY, @nid);