-
System Tray Icons
Hello,
I'm thinking about making a small utility, however I need to know how to place an icon in the system tray. Also, how can I catch clicks on the icon.
Any tutorials or sample source code would be humbly welcome - anything that I can put in my BOOL CALLBACK function to catch clicks on the icon.
Thanks,
Chris. :)
-
You need the Shell_NotifyIcon() function. There's an MSDN article with some info -
http://msdn.microsoft.com/library/de...nt/Taskbar.asp
-
Try the following example code....
#include <windows.h>
#include <shellapi.h>
#define WM_SHELLNOTIFY WM_USER+5
#define IDI_TRAY 0
#define IDMI_RESTORE 1001
#define IDMI_CLOSE 1002
NOTIFYICONDATA note;
BOOL CALLBACK WndProc(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam)
{
POINT pt;
HMENU hPopupMenu = CreatePopupMenu();
AppendMenu(hPopupMenu, MF_STRING, IDMI_RESTORE, "Restore");
AppendMenu(hPopupMenu, MF_STRING, IDMI_CLOSE, "Close Program");
switch (umsg)
{
case WM_COMMAND:
. . .
. . .
if (lParam == 0)
{
Shell_NotifyIcon(NIM_DELETE, ¬e);
if (LOWORD (wParam) == IDMI_RESTORE)
{
ShowWindow(hwnd, SW_RESTORE);
}
}
return true;
case WM_SIZE:
if (wParam == SIZE_MINIMIZED)
{
note.cbSize = sizeof(NOTIFYICONDATA);
note.hWnd = hWnd;
note.uID = IDI_TRAY;
note.uFlags = NIF_ICON+NIF_MESSAGE+NIF_TIP;
note.uCallbackMessage = WM_SHELLNOTIFY;
note.hIcon = LoadIcon(TheInstance, MAKEINTRESOURCE(IDI_YOUR_ICON));
lstrcpy(¬e.szTip[0], "Right click for menu, left click to restore...");
ShowWindow(hwnd, SW_HIDE);
Shell_NotifyIcon(NIM_ADD, ¬e);
}
return true;
case WM_SHELLNOTIFY:
if (wParam == IDI_TRAY)
{
if (lParam == WM_RBUTTONDOWN)
{
GetCursorPos(&pt);
TrackPopupMenu(hPopupMenu, TPM_RIGHTALIGN, pt.x, pt.y, 0, hwnd, NULL);
}
else if (lParam == WM_LBUTTONDOWN)
{
SendMessage(hwnd, WM_COMMAND, IDMI_RESTORE, 0);
}
}
else DefWindowProc(hwnd, umsg, wParam, lParam);
return true;
. . .
. . .
}
return false;
}
Forgive the formatting, this was quickly thrown together.
-
Second parameter of Shell_NotifyIcon() function is the address of the "note" NOTIFYICONDATA structure.
-
Oops
I figured out how to use it the other day from some example source code, I really should have said so, sorry. Thanks for the example anyway, it's made things even more clear to me.
Thanks,
Chris :)
-
For anyone interested, there is still another error in what I previously posted...
case WM_COMMAND:
. . .
. . .
if (lParam == 0)
{
Shell_NotifyIcon(NIM_DELETE, ¬e);
if (LOWORD (wParam) == IDMI_RESTORE)
{
ShowWindow(hwnd, SW_RESTORE);
}
DestroyWindow(hwnd); // forgot this line
}
return true;
If you click the "Close Program" option from the SysTray icon, nothing will happen without DestroyWindow().