龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > VC开发 >

利用Visual C++实现系统托盘程序(2)

时间:2009-12-30 15:42来源:未知 作者:admin 点击:
分享到:
二、编程步骤 1、 启动Visual C++6.0,生成一个单文档的应用程序TrayTest,取消文档视图支持; 2、 在CMainFrame类中添加自定义消息#define WM_MY_TRAY_NOTIFICATION WM_
二、编程步骤

  1、 启动Visual C++6.0,生成一个单文档的应用程序TrayTest,取消文档视图支持;

  2、 在CMainFrame类中添加自定义消息#define WM_MY_TRAY_NOTIFICATION WM_USER+0,并在该类中为此自定义消息手动添加消息映射ON_MESSAGE(WM_MY_TRAY_NOTIFICATION, OnTrayNotification)和消息响应函数afx_msg LRESULT OnTrayNotification(WPARAM wp, LPARAM lp);

  3、 设计二个图标添加到项目中,其ID标志分别为"IDI_MYICON"、"IDI_MYICON2",作为托盘显示时的图标;

  4、 在CMainFrame类中添加下述变量: CTrayIcon m_trayIcon(用来操作图标的类对象)、CEdit m_wndEdit(编辑框用来显示所跟踪到的鼠标消息)、int m_iWhichIcon(决定当前托盘使用哪个图标)、BOOL m_bShutdown(是否关闭当前拖盘程序标志)、BOOL m_bShowTrayNotifications(是否显示托盘消息标志);

  5、 为程序的IDR_MAINFRAME添加处理菜单项和托盘的上下文菜单IDI_TRAYICON(具体的菜单项的标题和ID标志符参见代码部分),然后使用Class Wizard为各个菜单项添加处理函数;

  6、 添加代码,编译运行程序。

///////////////////////////////////////////////CTrayIcon类的头文件;
#ifndef _TRAYICON_H
#define _TRAYICON_H
class CTrayIcon : public CCmdTarget {
 protected:
  DECLARE_DYNAMIC(CTrayIcon)
  NOTIFYICONDATA m_nid; // struct for Shell_NotifyIcon args
 public:
  CTrayIcon(UINT uID);
  ~CTrayIcon();
  // Call this to receive tray notifications
  void SetNotificationWnd(CWnd* pNotifyWnd, UINT uCbMsg);
  BOOL SetIcon(UINT uID); // main variant you want to use
  BOOL SetIcon(HICON hicon, LPCSTR lpTip);
  BOOL SetIcon(LPCTSTR lpResName, LPCSTR lpTip)
  { return SetIcon(lpResName ?
   AfxGetApp()->LoadIcon(lpResName) : NULL, lpTip); }
  BOOL SetStandardIcon(LPCTSTR lpszIconName, LPCSTR lpTip)
  { return SetIcon(::LoadIcon(NULL, lpszIconName), lpTip); }
  virtual LRESULT OnTrayNotification(WPARAM uID, LPARAM lEvent);
};
#endif
///////////////////////////////////////////////////CTrayIcon类的.CPP文件
#include "stdafx.h"
#include "trayicon.h"
#include // for AfxLoadString
IMPLEMENT_DYNAMIC(CTrayIcon, CCmdTarget)
CTrayIcon::CTrayIcon(UINT uID)
{
 memset(&m_nid, 0 , sizeof(m_nid)); // Initialize NOTIFYICONDATA
 m_nid.cbSize = sizeof(m_nid);
 m_nid.uID = uID; // never changes after construction
 AfxLoadString(uID, m_nid.szTip, sizeof(m_nid.szTip));
 // Use resource string as tip if there is one
}

CTrayIcon::~CTrayIcon()
{
 SetIcon(0); // remove icon from system tray

}

void CTrayIcon::SetNotificationWnd(CWnd* pNotifyWnd, UINT uCbMsg)
{
 // Set notification window. It must created already.
 ASSERT(pNotifyWnd==NULL    ::IsWindow(pNotifyWnd->GetSafeHwnd()));
 m_nid.hWnd = pNotifyWnd->GetSafeHwnd();
 ASSERT(uCbMsg==0    uCbMsg>=WM_USER);
 m_nid.uCallbackMessage = uCbMsg;
}

精彩图集

赞助商链接