//单元接口部分引用 SHELLAPI 函数:
//以下注释为我自己添加上去的,如果有描述错误的地方还需要更正
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, shellapi, Menus, StdCtrls;
const
wi_iconeven = wm_user + 1000;//定义消息常量,用来接受系统返回的消息.
type
TForm1 = class(TForm)
PopupMenu1: TPopupMenu;//有"显示"."隐藏","关闭"三种选项
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure FormCreate(Sender: TObject);
procedure N3Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure N2Click(Sender: TObject);
procedure iconclick(var message : TMessage); message wi_iconeven;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
nodedate : Tnotifyicondata;
implementation
{$R *.dfm}
//程序运行即显示托盘图标:
procedure TForm1.FormCreate(Sender: TObject);
begin
nodedate.cbSize := sizeof(tnotifyicondata);
nodedate.Wnd := handle;
nodedate.uID := 1;
nodedate.uFlags := Nif_Icon or Nif_Message or Nif_Tip;
nodedate.uCallbackMessage := wi_iconeven;
nodedate.hIcon := application.Icon.Handle;
nodedate.szTip := '托盘图标测试';
Shell_NotifyIcon(NIM_ADD,@nodedate);
n1.Checked := true;
end;
//"关闭"
procedure TForm1.N3Click(Sender: TObject);
begin
Shell_NotifyIcon(NIM_DELETE,@nodedate);
Application.Terminate;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
//释放内存
Shell_NotifyIcon(NIM_DELETE,@nodedate);
end;
//点击'显示'
procedure TForm1.N1Click(Sender: TObject);
begin
n1.Checked := true;
n2.Checked := false;
ShowWindow(Application.Handle,SW_SHOW);
ShowWindow(form1.Handle, SW_SHOW);
end;
//"隐藏" 窗口
procedure TForm1.N2Click(Sender: TObject);
begin
n1.Checked := false;
n2.Checked := true;
ShowWindow(Application.Handle, SW_HIDE);
ShowWindow(form1.Handle, SW_HIDE);
end;
//接受消息
procedure TForm1.iconclick(var message: TMessage);
var P: Tpoint;
begin
if message.LParam = WM_RButtonUP then // 按下鼠标右键:
begin
SetForegroundWindow(From1.Handle); // 这句一定要加,否则弹出菜单不会自动隐藏
GetCursorPos(P);//获取鼠标坐标
PopupMenu1.Popup(P.x, P.y);//将 Popupmenu 与鼠标关联
end;
if message.LParam = WM_LButtonUP then
begin
if form1.Showing then
form1.Hide
else if not form1.Showing then
form1.Show;
end;
end;
end.
注 : 如果想讓你的托盤圖標可以在想更換的時候更換,可以通過一下方式修改.
nodedate.hIcon := icon.Handle;
Shell_NotifyIcon(NIM_MODIFY,@nodedate);
另:如何加載自定義的圖片?
var icon : Ticon;
.....
icon := Ticon.Create;
icon.LoadFromFile(extractfilepath(application.ExeName) + '\icon1.ico');//加載本目錄下的ico文件;