Josh Posted August 3 Posted August 3 #include <windows.h> #include <shellapi.h> #define WM_TRAYICON (WM_USER + 1) #define ID_TRAY_APP_ICON 1001 #define ID_MENU_EXIT 101 #define ID_MENU_OPTION1 102 #define ID_MENU_OPTION2 103 // Global variables NOTIFYICONDATA nid; HMENU hPopupMenu; // Forward declarations LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI main(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Register window class WNDCLASS wc = { 0 }; wc.lpfnWndProc = WndProc; wc.hInstance = hInstance; wc.lpszClassName = L"TrayAppClass"; RegisterClass(&wc); // Create window (hidden) HWND hwnd = CreateWindow(wc.lpszClassName, L"TrayApp", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 300, 200, NULL, NULL, hInstance, NULL); // Initialize NOTIFYICONDATA ZeroMemory(&nid, sizeof(nid)); nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = hwnd; nid.uID = ID_TRAY_APP_ICON; nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; nid.uCallbackMessage = WM_TRAYICON; // Load icon HICON hIcon = LoadIcon(NULL, IDI_APPLICATION); nid.hIcon = hIcon; // Set tooltip lstrcpy(nid.szTip, L"My Tray Icon"); // Add icon to system tray Shell_NotifyIcon(NIM_ADD, &nid); // Create popup menu hPopupMenu = CreatePopupMenu(); AppendMenu(hPopupMenu, MF_STRING, ID_MENU_OPTION1, L"Option 1"); AppendMenu(hPopupMenu, MF_STRING, ID_MENU_OPTION2, L"Option 2"); AppendMenu(hPopupMenu, MF_SEPARATOR, 0, NULL); AppendMenu(hPopupMenu, MF_STRING, ID_MENU_EXIT, L"Exit"); // Message loop MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } // Cleanup Shell_NotifyIcon(NIM_DELETE, &nid); DestroyIcon(hIcon); DestroyMenu(hPopupMenu); return (int)msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_TRAYICON: { if (lParam == WM_LBUTTONUP) { // Left click - optional: show message or do something } else if (lParam == WM_RBUTTONUP) { // Right click - show context menu POINT pt; GetCursorPos(&pt); SetForegroundWindow(hwnd); // Needed for menu to work properly TrackPopupMenu(hPopupMenu, TPM_RIGHTBUTTON, pt.x, pt.y, 0, hwnd, NULL); } break; } case WM_COMMAND: { switch (LOWORD(wParam)) { case ID_MENU_OPTION1: MessageBox(NULL, L"Option 1 selected", L"Info", MB_OK); break; case ID_MENU_OPTION2: MessageBox(NULL, L"Option 2 selected", L"Info", MB_OK); break; case ID_MENU_EXIT: PostMessage(hwnd, WM_CLOSE, 0, 0); break; } break; } case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0; } Quote Let's build cool stuff and have fun.
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.