源代码下载
一、简介
有时我们需要在非客户区(例如:标题栏)添加按钮,并对按钮作出响应,如下图所示:
为此我封装了两个类CNCButton和CNCButtonManager,CNCButton主要用于按钮绘制,CNCButtonManager用于按钮的管理并对非客户区的消息进行处理。如下是几个主要的非客户区消息:
WM_NCHITTEST
WM_NCACTIVATE
WM_NCPAINT
二、使用
2.1 首先我们需要引用两个类的头文件
#include"NCButtonManager.h"
#include "NCButton.h"
2.2 为按钮定义ID
#define ID_BUTTON1 100
#define ID_BUTTON2 101
#define ID_BUTTON3 102
2.3 添加按钮和管理类成员变量
// Implementation
public:
CNCButtonm_NcButton1;
CNCButtonm_NcButton2;
CNCButtonm_NcButton3;
CNCButtonManagerm_NcButtonManager;
2.4 创建按钮
// 按钮的位置和尺寸
POINT ptBtn1Offset = {120, 10};
POINT ptBtn2Offset = {20, 32};
POINT ptBtn3Offset = {190, 10};
SIZE sizeBtn1 = {60, 14};
SIZE sizeBtn2 = {16, 14};
SIZE sizeBtn3 = {16, 14};
// 创建按钮
m_NcButton1.Create("",this->m_hWnd, ptBtn1Offset, sizeBtn1, ID_BUTTON1);
m_NcButton2.Create("", this->m_hWnd,ptBtn2Offset, sizeBtn2, ID_BUTTON2);
m_NcButton3.Create("",this->m_hWnd, ptBtn3Offset, sizeBtn3, ID_BUTTON3);
// 设置文字、提示、按钮位图
m_NcButton1.SetText("VC知识库", "宋体", 12);
m_NcButton1.SetTooltip("VC知识库欢迎您!");
m_NcButton2.SetButtonBitmap(IDB_PEN1,BTNBMP_NORMAL); // 正常位图
m_NcButton2.SetButtonBitmap(IDB_PEN2,BTNBMP_MOUSEOVER); // 鼠标移到上面时的位图
m_NcButton2.SetTooltip("pen");
m_NcButton3.SetButtonBitmap(IDB_PEN1,BTNBMP_NORMAL);
m_NcButton3.SetButtonBitmap(IDB_PEN2,BTNBMP_MOUSEOVER);
m_NcButton3.SetTooltip("pen");
// 添加到管理类
m_NcButtonManager.AddButton(&m_NcButton1);
m_NcButtonManager.AddButton(&m_NcButton2);
m_NcButtonManager.AddButton(&m_NcButton3);
2.5 消息的处理
2.5.1 将消息转发给管理类
LRESULTCMainFrame::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULTlResult = CFrameWnd::DefWindowProc(message, wParam, lParam);
if(!IsWindow(this->m_hWnd))
returnlResult;
LRESULTlMyResult = m_NcButtonManager.DefWindowProc(this->m_hWnd, message, wParam,lParam);
if(lMyResult!= 0)
returnlMyResult;
else
returnlResult;
}
2.5.2 添加消息处理函数
// Operations
public:
voidOnNcButton1Clicked();
voidCMainFrame::OnNcButton1Clicked()
{
AfxMessageBox("VC知识库欢迎您! www.vckbase.com");
}
2.5.3 消息映射
BEGIN_MESSAGE_MAP(CMainFrame,CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
ON_BN_CLICKED(ID_BUTTON1,OnNcButton1Clicked)
ON_BN_CLICKED(ID_BUTTON2,OnNcButton2Clicked)
ON_BN_CLICKED(ID_BUTTON3,OnNcButton3Clicked)
ON_WM_CREATE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
总结:本文提供的两个类可以方便地往非客户区(如:标题栏)添加按钮,欢迎批评指正!