unit UShellNotifyIcon;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs,
StdCtrls, Registry, Menus, ShellApi, ExtCtrls;
var
WM_NotifyIcon: Cardinal;
type
TShellNotifyIcon=Class
private
FHwnd:THandle;
NotifyIcon: TNotifyIconData;
FHintStr:String;
FIcoMenu: TPopupMenu;
procedure setHwnd(const Value: THandle);
procedure setHintStr(const Value: String);
procedure setIcoMenu(const Value: TPopupMenu);
procedure WndProc(var Msg: TMessage);
protected
public
procedure LoadAppIcon;
procedure UnLoadIcon;
procedure ModifyIcon(IcoHandle:THandle);
procedure ModifyHint(Hint:String);
procedure ShowMainFrm(Show:Boolean);
property MHwnd:THandle read FHwnd write setHwnd;
property HintStr:String read FHintStr write setHintStr;
property IcoMenu:TPopupMenu read FIcoMenu write setIcoMenu;
end;
var
ShellNotifyIcon:TShellNotifyIcon;
implementation
{ TShellNotifyIcon }
{添加托盘}
procedure TShellNotifyIcon.LoadAppIcon;
var
s: string;
begin
with NotifyIcon do
begin
cbSize := SizeOf(TNotifyIconData);
Wnd := Classes.AllocateHWnd(WndProc);
uID := 1;
uFlags := NIF_ICON or NIF_MESSAGE or NIF_TIP;
uCallBackMessage := WM_NotifyIcon;
hIcon := Application.Icon.Handle;
s := HintStr;
StrLCopy(szTip, PAnsiChar(s), Length(s));
end;
Shell_NotifyIcon(NIM_ADD, @NotifyIcon);
end;
{窗口显示}
procedure TShellNotifyIcon.ShowMainFrm(Show:Boolean);
begin
if Show then
begin
ShowWindow(Application.Handle, SW_SHOW);
Application.Restore;
ShowWindow(MHwnd, SW_SHOW);
SetForegroundWindow(MHwnd);
end else
begin
ShowWindow(Application.Handle, SW_HIDE);
ShowWindow(MHwnd, SW_HIDE);
Application.Minimize;
end;
end;
{消息处理}
procedure TShellNotifyIcon.WndProc(var Msg: TMessage);
var
mp: TPoint;
begin
if Msg.Msg=WM_NotifyIcon then
begin
if Msg.LParam = WM_LBUTTONDBLCLK then
begin
ShowMainFrm(True);
end else if Msg.LParam = WM_RBUTTONUP then
begin
GetCursorPos(mp);
SetForegroundWindow(MHwnd); {解决弹出右键菜单后不操作不消失问题}
IcoMenu.Popup(mp.X, mp.Y);
end else Inherited;
end;
end;
{修改显示}
procedure TShellNotifyIcon.ModifyHint(Hint: String);
begin
StrLCopy(NotifyIcon.szTip,PChar(Hint),Length(Hint));
Shell_NotifyIcon(NIM_MODIFY, @NotifyIcon);
end;
{修改托盘}
procedure TShellNotifyIcon.ModifyIcon(IcoHandle:THandle);
begin
NotifyIcon.hIcon:=IcoHandle;
Shell_NotifyIcon(NIM_MODIFY, @NotifyIcon);
end;
{删除托盘}
procedure TShellNotifyIcon.UnLoadIcon;
begin
Shell_NotifyIcon(NIM_DELETE, @NotifyIcon);
end;
procedure TShellNotifyIcon.setHintStr(const Value: String);
begin
FHintStr := Value;
end;
procedure TShellNotifyIcon.setHwnd(const Value: THandle);
begin
FHwnd := Value;
end;
procedure TShellNotifyIcon.setIcoMenu(const Value: TPopupMenu);
begin
FIcoMenu := Value;
end;
{ NotifyIcon.hIcon := Application.Icon.Handle;
Shell_NotifyIcon(NIM_MODIFY, @NotifyIcon);}
initialization
WM_NotifyIcon := RegisterWindowMessage('NotifyIcon');
end.