// TrayIcon.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "TrayIcon.h"
#include "shellapi.h"
#define MAX_LOADSTRING 100
#define WM_TASKBAR WM_APP + 1000
HINSTANCE hInst; // current instance
HWND mainForm; // Main Window Handle
BOOL CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void AddIcon();
void DeleteIcon();
void RestoreWindow();
void HideWindow();
enum WindowStatus
{
WFormal,
WTrayIcon
};
WindowStatus wStatus = WFormal;
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// First Fill Our Global Instance.
hInst = hInstance;
::DialogBoxParam(hInstance, (LPCWSTR)IDD_MainDlg, NULL,WndProc, NULL);
::ExitProcess(0);
return 1;
}
BOOL CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static HMENU hMenu ;
switch (message)
{
case WM_INITDIALOG:
mainForm =hWnd;
HWND hIcon;
hIcon = (HWND)::LoadIcon(hInst, NULL);
if (hIcon)
{
::SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM) (HICON)hIcon);
}
hMenu = LoadMenu (hInst, (LPCWSTR)IDC_TRAYICON) ;
hMenu = GetSubMenu (hMenu, 0) ;
break;
case WM_COMMAND:
if (wParam == IDHIDE)
{
//::SendMessage(hWnd, WM_TASKBAR, NULL, NULL);
HideWindow();
}
else if (wParam == IDM_RESTORE)
{
RestoreWindow();
}
else if ((wParam == IDM_EXIT)||(wParam == IDCANCEL))
{
if (wStatus == WTrayIcon)
{
DeleteIcon();
}
::EndDialog(hWnd, NULL);
}
break;
case WM_TASKBAR:
if (lParam == WM_RBUTTONUP)
{
// If In TrayIcon Status Let's Pop Up Menu.
//::SetForegroundWindow(hWnd);
if (wStatus == WTrayIcon)
{
POINT point ;
GetCursorPos(&point);
TrackPopupMenu (hMenu, TPM_RIGHTBUTTON, point.x, point.y,
0, hWnd, NULL) ;
}
}
else if ((lParam == WM_LBUTTONDOWN)||(lParam == WM_LBUTTONDBLCLK))
{
// Let's Active Main Window Again.
RestoreWindow();
}
break;
default:
return FALSE;
}
//::InvalidateRect(hWnd, NULL, TRUE);
return TRUE;
}
void AddIcon()
{
HICON hTrayIcon = LoadIcon(hInst, (LPCWSTR)IDI_CUS);
BOOL bSucess =FALSE;
if (hTrayIcon)
{
NOTIFYICONDATA tnid;
tnid.cbSize = sizeof(NOTIFYICONDATA);
tnid.hWnd = mainForm;
tnid.uID = IDI_CUS;
tnid.uFlags = NIF_ICON|NIF_MESSAGE|NIF_TIP;
tnid.uCallbackMessage = WM_TASKBAR;
tnid.hIcon = hTrayIcon;
TCHAR tstring[] = TEXT("I am TryIcon");
//lstrcpyn(tnid.szTip,tstring,sizeof(tstring));
int size = sizeof(tnid.szTip);
lstrcpyn(tnid.szTip,tstring,sizeof(tnid.szTip)/2);
bSucess = Shell_NotifyIcon(NIM_ADD, &tnid);
}
wStatus = bSucess?WTrayIcon:WFormal;
}
void DeleteIcon()
{
BOOL bSucess =FALSE;
NOTIFYICONDATA tnid;
tnid.cbSize = sizeof(NOTIFYICONDATA);
tnid.hWnd = mainForm;
tnid.uID = IDI_CUS;
bSucess = Shell_NotifyIcon(NIM_DELETE, &tnid);
wStatus = WFormal;
}
void HideWindow()
{
if (wStatus == WFormal)
{
ShowWindow(mainForm, SW_HIDE);
AddIcon();
}
}
void RestoreWindow()
{
wStatus = WFormal;
ShowWindow(mainForm, SW_RESTORE);
::SetForegroundWindow(mainForm);
DeleteIcon();
}