托盘功能的实现(MFC)

托盘功能在很多地方都用到,比如我们每天用的 QQ ,当点击最小化的时候 QQ 主界面会自动隐藏,在桌面的右下角看到一个 QQ 图标,当双击 QQ 图片的时候又能将主界面显示出来。实现这种托盘功能的实现很简单,下面给出托盘功能的实现过程:

1在类中添加一个NOTIFYICONDATA类型的成员变量m_nid

protected:

HICONm_hIcon;

NOTIFYICONDATAm_nid;

2在类的初始化函数OnInitDialog中对结构体NOTIFYICONDATA进行初始化赋值

ZeroMemory(&m_nid,sizeof(m_nid));

m_nid.cbSize=sizeof(m_nid);

m_nid.hWnd=this->m_hWnd;

m_nid.uID=IDR_MAINFRAME;

m_nid.uFlags=NIF_ICON|NIF_MESSAGE|NIF_TIP;

m_nid.hIcon=LoadIcon(AfxGetInstanceHandle(),

MAKEINTRESOURCEA(IDR_MAINFRAME));

//WM_NOTIFYICON为点击托盘icon时产生的消息

m_nid.uCallbackMessage=WM_NOTIFYICON;

strcpy(m_nid.szTip,"hahaya");

3定义WM_NOTIFYICON的处理过程

#defineWM_NOTIFYICONWM_USER+100

virtualBOOLOnInitDialog();

afx_msgvoidOnSysCommand(UINTnID,LPARAMlParam);

afx_msgvoidOnPaint();

afx_msgHCURSOROnQueryDragIcon();

afx_msgvoidOnNotifyIcon(WPARAMwParam,LPARAMlParam);

ON_WM_SYSCOMMAND()

ON_WM_PAINT()

ON_WM_QUERYDRAGICON()

ON_MESSAGE(WM_NOTIFYICON,OnNotifyIcon)

void CMyDlg::OnNotifyIcon(WPARAM wParam, LPARAM lParam)

{

POINT pt;

GetCursorPos(&pt);

switch(lParam)
    {
        case WM_LBUTTONDBLCLK:

            ShowWindow(SW_SHOW);

            ShowWindow(SW_SHOWNORMAL);

            Shell_NotifyIcon(NIM_DELETE, &m_nid);

            break;
    }

}



4捕获发生在窗口上的窗口上大小发生变化的WM_SIZE消息(可以通过类向导给对话框添加WM_SIZE消息)

virtualBOOLOnInitDialog();

afx_msgvoidOnSysCommand(UINTnID,LPARAMlParam);

afx_msgvoidOnPaint();

afx_msgHCURSOROnQueryDragIcon();

afx_msgvoidOnNotifyIcon(WPARAMwParam,LPARAMlParam);

afx_msgvoidOnSize(UINTnType,intcx,intcy);

ON_WM_SYSCOMMAND()

ON_WM_PAINT()

ON_WM_QUERYDRAGICON()

ON_MESSAGE(WM_NOTIFYICON,OnNotifyIcon)

ON_WM_SIZE()

void CMyDlg::OnSize(UINT nType, int cx, int cy) 

{

CDialog::OnSize(nType, cx, cy);

// TODO: Add your message handler code here

if(nType == SIZE_MINIMIZED)
    {
        Shell_NotifyIcon(NIM_ADD, &m_nid);
        ShowWindow(SW_HIDE);
    }
}

你可能感兴趣的:(mfc)