为对话框创建工具栏
大家都知道,单文档应用程序默认生成了菜单栏和工具栏,而对话框应用程序则没有。对于菜单栏的添加比较简单,只要插入一个菜单资源然后在主对话框指定这个菜单就可以了。那么工具栏该如何创建呢?
工具栏的创建相对比较麻烦,在一本书上看到了创建工具栏较简单的方法,且听我细细给你道来。
1、从基类CToolBarCtrl中派生出所需要的类CstandardBar。
2、添加图片资源,目前编译器对24位位图支持不好,建议使用256色位图。大小视具体每个按钮的大小和个数而定。如果设定每个按钮的高为32像素,添加6个按钮,则插入的图片资源长度为192像素。对此,读者可自行设定。
现在我们添加五个按钮,高32像素,总长160像素。资源符号为IDR_STANDARDBAR。
3、添加字符串资源。
资源符号 值 字符串资源
IDSTR_JILU 102 记录
IDSTR_BAOCUN 103 保存
IDSTR_CHAZHAO 104 查找
IDSTR_CHAKAN 105 查看
IDSTR_QUIT 106 退出
在CstandardBar类中调用Create函数创建工具栏。代码如下:
BOOL CstandardBar::Create(DWORD dwStyle, const RECT &rect, CWnd *pParentWnd, UINT nID)
{
BOOL bRet = CToolBarCtrl::Create(dwStyle, rect, pParentWnd, nID);
m_nButtonCount = IDSTR_QUIT - IDSTR_JILU + 1;
SetBitmapSize( CSize(32,32) );
VERIFY(AddBitmap(m_nButtonCount,IDR_STANDARDBAR) != -1);
m_pTBButtons = new TBBUTTON[m_nButtonCount];
for (int nIndex = 0; nIndex < m_nButtonCount; nIndex++)
{
CString string;
string.LoadString(nIndex + IDSTR_JILU);
int nStringLength = string.GetLength() + 1;
TCHAR * pString = string.GetBufferSetLength(nStringLength);
pString[nStringLength] = 0;
pString[nStringLength-1] = 0;
VERIFY((m_pTBButtons[nIndex].iString = AddStrings(pString)) != -1);
string.ReleaseBuffer();
m_pTBButtons[nIndex].fsState =TBSTATE_ENABLED;
m_pTBButtons[nIndex].fsStyle =TBSTYLE_BUTTON;
m_pTBButtons[nIndex].dwData = 0;
m_pTBButtons[nIndex].iBitmap = nIndex;
m_pTBButtons[nIndex].idCommand = nIndex + IDSTR_JILU;
}
m_pTBButtons[m_nButtonCount-1].idCommand=IDCANCEL;
TBBUTTON sepButton;
sepButton.idCommand = 0;
sepButton.fsStyle = TBSTYLE_SEP;
sepButton.fsState = TBSTATE_ENABLED;
sepButton.iString = 0;
sepButton.iBitmap = 0;
sepButton.dwData = 0;
int nIndex;
for (nIndex = 0; nIndex < m_nButtonCount; nIndex++)
{
VERIFY(AddButtons(1,&m_pTBButtons[nIndex]));
if (!((nIndex +1) % 2))
{
VERIFY(AddButtons(1,&sepButton));
}
}
this->SetStyle(TBSTYLE_FLAT|CCS_TOP);
return bRet;
}
4、实例化CstandardBar对象:CstandardBar m_standardBar。注意要包含头文件#include “standardBar.h”
5、在主对话框为CstandardBar对象创建相应的窗口。代码如下:
int CToolBarDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialog::OnCreate(lpCreateStruct) == -1)
return -1;
m_standardBar.Create( WS_VISIBLE | WS_CHILD |WS_BORDER
|TBSTYLE_WRAPABLE | CCS_TOP | CCS_ADJUSTABLE,
CRect(0,0,0,0),this, IDR_STANDARDBAR);
m_standardBar.AutoSize();
return 0;
}
到此,工具栏的创建就大功告成了。以上代码都是我编译通过运行成功之后的,如果在你编译过程中出现错误,可在文末留言,我会尽力帮你解决。如果网友想要此工程的源代码,可留下你的电子邮件,我会抽时间给你发过去。
程序运行效果如下图: