備忘録

備忘録

タスクトレイのアイコンを消す方法

Ⅰ. はじめに

タイトルの通り「タスクトレイのアイコンを消す方法」です。

f:id:kagasu:20180503091733p:plain

Ⅱ. やり方

C++の場合
#include <Windows.h>

int main()
{
  auto hWnd = FindWindow(L"ApplicationWindow", NULL);
  
  NOTIFYICONDATA data;
  data.cbSize = sizeof(NOTIFYICONDATA);
  data.hWnd = hWnd;
  data.uID = 1;

  Shell_NotifyIcon(NIM_DELETE, &data);

  return 0;
}
C#の場合
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string className, string windowName);

[DllImport("shell32.dll")]
static extern bool Shell_NotifyIcon(uint dwMessage, ref NOTIFYICONDATA pnid);

[StructLayout(LayoutKind.Sequential)]
public struct NOTIFYICONDATA
{
  public uint cbSize;
  public IntPtr hWnd;
  public uint uID;
  public uint uFlags;
  public uint uCallbackMessage;
  public IntPtr hIcon;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
  public string szTip;
  public uint dwState;
  public uint dwStateMask;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]a
  public string szInfo;
  public uint uVersion;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
  public string szInfoTitle;
  public uint dwInfoFlags;
  public Guid guidItem;
  public IntPtr hBalloonIcon;
}

static void Main(string[] args)
{
  uint NIM_DELETE = 0x2;
  var hWnd = FindWindow("ApplicationWindow", null);
  var data = new NOTIFYICONDATA();
  data.cbSize = (uint)Marshal.SizeOf(typeof(NOTIFYICONDATA));
  data.hWnd = hWnd;
  data.uID = 1;

  var ret = Shell_NotifyIcon(NIM_DELETE, ref data);
}

その他

NOTIFYICONDATAのuIDについて

uID の値はアプリケーションによって異なります。
API Monitor 等を利用して対象アプリケーションの Shell_NotifyIcon をhookする事で調べることが出来ます。