您的位置:首页 > 其它

[VC]基于对话框程序,自定义工具栏(支持真彩色图标,可添加文字)

2011-05-31 11:05 148 查看
转载自 ewook
最终编辑 ewook

应该是一个老生常谈的问题了,仍然决定写一写的原因是:在网上搜一搜,讲得有效易懂的还真没发现(可能是大虾们都懒得去写。。。)

动机:传统的VC工具栏只支持16色的图标,且不能添加文字。

要点:CToolBarCtrl类的使用。先引用MSDN上的话(翻译水平比较菜,见谅!)

使用CToolBarCtrl类,一般遵从以下几个步骤:
1.构造一个CToolBarCtrl对象。
2.调用Create函数创建Windows工具条通用控件并与CToolBarCtrl对象相关联。
3.确定工具条上的按钮如何显示:
(1)使用位图图像。调用AddBitmap向工具条添加按钮位图
(2)使用图像列表里面显示的图像。调用SetImageList函数、SetHotImageList函数、SetDisabledImageList函数指定图像列表
(3)作用字符串标签。调用AddString和(或)AddStrings函数为工具栏添加字符串
4.调用AddButtons函数为工具条添加按钮结构
5.如果需要为不是CFrameWnd的拥有窗口添加工具提示,需要在工具条拥有窗口中传递TTN_NEEDTEXT消息,该消息在CToolBarCtrl: Handling Tool Tip Notifications中有所描述。

步骤:1.将要作为工具栏图标的位图或图标导入到VC资源管理器中。

2.在C***Dlg类为添加两个成员变量:CImageList m_ImageList,CToolBarCtrl m_ToolBar

3.在OnInitDialog()函数中添加如下代码:

/***************************************创建工具栏********************************************/
CBitmap bm;
UINT Resource[3]={IDB_BITMAP1,IDB_BITMAP2,IDB_BITMAP3}; //位图ID数组
int i;

m_ImageList.Create(32,32,ILC_COLOR24|ILC_MASK,0,0); //创建Image List
m_ToolBar.Create(TBSTYLE_FLAT | CCS_TOP | WS_CHILD | WS_VISIBLE | WS_BORDER | CCS_ADJUSTABLE,CRect(0,0,0,0),this,IDR_TOOLBAR); //创建Toolbar Control
m_ToolBar.SetBitmapSize(CSize(32,32));

for(i=0;i<3;i++)
{
bm.LoadBitmap(Resource[i]);
m_ImageList.Add(&bm,(CBitmap *)NULL);
bm.Detach();
}

m_ToolBar.SetImageList(&m_ImageList);

TBBUTTON Buttons[3]; //定义TBBUTTON结构体数组
CString str;

for(i=0;i<3;i++)
{
str.LoadString(IDS_FILE+i); //IDS_FILE是在String Table中添加的String
Buttons[i].iString=m_ToolBar.AddStrings(str);
Buttons[i].dwData=0;
Buttons[i].fsState=TBSTATE_ENABLED;
Buttons[i].fsStyle=TBSTYLE_BUTTON;
Buttons[i].iBitmap=i;
Buttons[i].idCommand=IDS_FILE+i; //按钮命令响应
}
m_ToolBar.AddButtons(3,Buttons);
m_ToolBar.AutoSize();

m_ToolBar.ShowWindow(SW_SHOW);
/***************************************创建工具栏********************************************/

3.最终效果如图:



注解:TBBUTTON是定义工具条按钮的结构体,声明如下:
typedef struct _TBBUTTON {
int iBitmap;// zero-based index of button image
int idCommand;  // command to be sent when button pressed
BYTE fsState;     // button state--see below
BYTE fsStyle;     // button style--see below
DWORD dwData;     // application-defined value
int iString;// zero-based index of button label string
} TBBUTTON;

调用AddButtons函数向工具栏添加按钮。函数原型如下:

BOOL AddButtons( int nNumButtons, LPTBBUTTON lpButtons );

其中nNumButtons是要添加的按钮数目,lpButtons是指向TBBUTTON结构体的指针。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: