Windows UI - TrayIcon Window

本文介绍了一个使用C++实现的托盘图标应用程序。该程序能在任务栏显示一个图标,并通过右键菜单实现窗口隐藏与恢复等功能。文章详细展示了如何创建托盘图标、处理消息循环以及实现窗口状态切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// TrayIconWindow.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "TrayIconWindow.h"
#include "shellapi.h"
#define MAX_LOADSTRING 100
#define WM_TASKBAR WM_APP + 1000
// Global Variables:
HINSTANCE hInst;        // current instance
HWND mainForm;
TCHAR szTitle[MAX_LOADSTRING];     // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];   // the main window class name

enum WindowStatus
{
 WFormal,
 WTrayIcon
};

 

WindowStatus wStatus = WFormal;
// Forward declarations of functions included in this code module:
ATOM    MyRegisterClass(HINSTANCE hInstance);
BOOL    InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void AddIcon();
void DeleteIcon();
void RestoreWindow();
void HideWindow();
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
 UNREFERENCED_PARAMETER(hPrevInstance);
 UNREFERENCED_PARAMETER(lpCmdLine);

  // TODO: Place code here.
 MSG msg;

 // Initialize global strings
 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
 LoadString(hInstance, IDC_TRAYICONWINDOW, szWindowClass, MAX_LOADSTRING);
 MyRegisterClass(hInstance);

 // Perform application initialization:
 if (!InitInstance (hInstance, nCmdShow))
 {
  return FALSE;
 }


 // Main message loop:
 while (GetMessage(&msg, NULL, 0, 0))
 {
  
   TranslateMessage(&msg);
   DispatchMessage(&msg);
  
 }

 return (int) msg.wParam;
}

 

//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
 WNDCLASSEX wcex;

 wcex.cbSize = sizeof(WNDCLASSEX);

 wcex.style   =  CS_HREDRAW | CS_VREDRAW;
 wcex.lpfnWndProc = WndProc;
 wcex.cbClsExtra  = 0;
 wcex.cbWndExtra  = 0;
 wcex.hInstance  = hInstance;
 wcex.hIcon   = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TRAYICONWINDOW));
 wcex.hCursor  = LoadCursor(NULL, IDC_ARROW);
 wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
 wcex.lpszMenuName = NULL;
 wcex.lpszClassName = szWindowClass;
 wcex.hIconSm  = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); 
 return RegisterClassEx(&wcex);


}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;
   hInst = hInstance; // Store instance handle in our global variable
   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }
   ShowWindow(hWnd,SW_HIDE);   //hide   main   window  
   UpdateWindow(hWnd);  
  return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND - process the application menu
//  WM_PAINT - Paint the main window
//  WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{

 static HMENU hMenu;
 switch (message)
 {
  
 case WM_CREATE:
  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) ;
  AddIcon();
  break;;
 
 case WM_SIZE:
  if (wParam == SIZE_MINIMIZED)
  {
   HideWindow();
  }
  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, IDC_TRAYICONWINDOW, point.x, point.y,
     0, hWnd, NULL) ;

   }
  }
  else if ((lParam == WM_LBUTTONDOWN)||(lParam == WM_LBUTTONDBLCLK))
  {
   // Let's Active Main Window Again.
   RestoreWindow();

  }

  break;

 case WM_COMMAND:
 
      if (wParam == IDM_EXIT)
  {

   if (wStatus == WTrayIcon)
   {
    DeleteIcon();

   }
   ::DestroyWindow(mainForm);
  }  
  break;
 case WM_DESTROY:
  DeleteIcon();
  PostQuitMessage(0);
  break;

 default:
  return DefWindowProc(hWnd, message, wParam, lParam);
 }
 return 0;
}

// Message handler for about box.
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 RestoreWindow()
{
 wStatus = WFormal;
 ShowWindow(mainForm, SW_RESTORE);
 ::SetForegroundWindow(mainForm);
 DeleteIcon();
}

void HideWindow()
{
 if (wStatus == WFormal)
 {
  ShowWindow(mainForm, SW_HIDE);
  AddIcon();
 }

trayicon类的使用 //新建一个基于单文档的工程 //将trayicon类引入工程,并引入图标作为动态显示用 //在工程中新建一个菜单ID为IDR_TRAYPOPUP,添加两个命令ID:ID_SHOWWINDOW 和 ID_HIDEWINDOW //并利用类向导在CMainFrame类中为它们添加命令处理函数 void CMainFrame::OnShowwindow() { // 显示窗口 this->ShowWindow(SW_SHOW); } void CMainFrame::OnHidewindow() { // 隐藏窗口 this->ShowWindow(SW_HIDE); } //在类CMainFrame头文件前添加 #include "ntray.h" #define MAXICONS (int)9 //定义图标的最大数目,具体工程具体修改数目 #define DELAY (DWORD)100 //定义动画图标的时间延迟 //在DECLARE_MESSAGE_MAP()前添加自定义消息 afx_msg LRESULT OnTrayNotification(WPARAM wParam, LPARAM lParam); //声明trayicon类对象 CTrayNotifyIcon m_TrayIcon; //声明图标数组 HICON m_hIcons[MAXICONS]; //在CMainFrame的实现文件中添加消息宏ID #define WM_TRAYNOTIFY (WM_USER + 100) //在BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) 和 END_MESSAGE_MAP()之间添加消息映射 ON_MESSAGE(WM_TRAYNOTIFY, OnTrayNotification) //在CMainFrame的实现文件中定义消息处理函数 LRESULT CMainFrame::OnTrayNotification(WPARAM wParam, LPARAM lParam) { //Delegate all the work back to the default implementation in //CTrayNotifyIcon. return m_TrayIcon.OnTrayNotification(wParam, lParam); } //在CMainFrame的构造函数中添加icon的初始化代码 for (int i=0; i<MAXICONS; i++) { //任务栏图标,注意引入的图标的ID值为连续的,且IDI_ICON1的值为图标ID中最小的 m_hIcons[i] = AfxGetApp()->LoadIcon(IDI_ICON1 + i); } //在CMainFrame的OnCreate(LPCREATESTRUCT lpCreateStruct) 函数中添加 if (!m_TrayIcon.Create(this, IDR_TRAYPOPUP, _T("提示信息"), m_hIcons, MAXICONS, DELAY, WM_TRAYNOTIFY)) { AfxMessageBox(_T("Failed to create tray icon"), MB_OK | MB_ICONSTOP); return -1; } //在需要使用动态图标或静态图标处加入以下代码 if (m_TrayIcon.UsingAnimatedIcon())//判断是否处于动态显示状态 { m_TrayIcon.SetIcon(m_hIcons[0]);//设置通知区为静态图标 m_TrayIcon.SetTooltipText(_T("静止也美!")); } else { m_TrayIcon.SetIcon(m_hIcons, MAXICONS, DELAY);//设置通知区为动态图标 m_TrayIcon.SetTooltipText(_T("运动才美!")); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值