显示系统托盘列表(并执行隐藏与显示)

代码文件:


unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    ListView1: TListView;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses Commctrl;

{获取托盘句柄的函数}
function TrayHWnd: HWND;
var
  h,hTmp: HWND;
begin
  h := FindWindow('Shell_TrayWnd', nil);
  h := FindWindowEx(h, 0, 'TrayNotifyWnd', nil);
  hTmp := FindWindowEx(h, 0, 'SysPager', nil);
  if hTmp <> 0 then h := hTmp;
  hTmp := FindWindowEx(h, 0, 'ToolbarWindow32', nil);
  if hTmp <> 0 then h := hTmp;
  Result := h;
end;

{控件初始化}
procedure TForm1.FormCreate(Sender: TObject);
begin
  ListView1.Align := alLeft;
  ListView1.Columns.Add;
  ListView1.Columns.Items[0].Caption := '托盘图标列表';
  ListView1.Columns.Items[0].Width := 500;
  Listview1.ViewStyle := vsReport;

  Button1.Caption := '显示托盘列表';
  Button2.Caption := '全部隐藏';
  Button3.Caption := '取消隐藏';
  Button2.Enabled := False;
  Button3.Enabled := False;
end;

{提取列表}
procedure TForm1.Button1Click(Sender: TObject);
var
  h: HWND;
  count,size,num: Cardinal;
  pid, ph: Cardinal;
  p: Pointer;
  icoBtn: TTBButton;
  buf: array[0..255] of WideChar;
  i: Integer;
  item: TListItem;
begin
  h := TrayHWnd;
  count := SendMessage(h, TB_BUTTONCOUNT, 0, 0);
  size := SizeOf(TTBButton);

  GetWindowThreadProcessId(h, pid);
  ph := OpenProcess(PROCESS_VM_READ, False, pid);

  for i := 0 to count - 1 do
  begin
    SendMessage(h, TB_GETBUTTON, i, DWORD(p));
    ReadProcessMemory(ph, p, @icoBtn, size, num);
    ReadProcessMemory(ph, Pointer(icoBtn.iString), @buf, Length(buf)*SizeOf(buf[0]), num);
    item := ListView1.Items.Add;
    item.Caption := buf;
  end;
  CloseHandle(ph);

  Button2.Enabled := True;
  Button3.Enabled := True;
end;

{全部隐藏}
procedure TForm1.Button2Click(Sender: TObject);
var
  h: HWND;
  count,i: Cardinal;
begin
  h := TrayHWnd;
  count := SendMessage(h, TB_BUTTONCOUNT, 0, 0);
  for i := 0 to count - 1 do SendMessage(h, TB_HIDEBUTTON, i, 1);
end;

{全部显示}
procedure TForm1.Button3Click(Sender: TObject);
var
  h: HWND;
  count,i: Cardinal;
begin
  h := TrayHWnd;
  count := SendMessage(h, TB_BUTTONCOUNT, 0, 0);
  for i := 0 to count - 1 do SendMessage(h, TB_HIDEBUTTON, i, 0);
end;

end.

原文地址:https://www.cnblogs.com/shijiaoyun/p/3844344.html