尽管在大多数的Windows应用程序中工具栏无处不见,但是工具栏通常只在应用程序的主窗口上出现,而不在任何对话框中出现。因此,为MFC的对话框增加一个工具栏就比较麻烦了。
该问题的解决分为两部分:第一,为对话框增加一个工具栏;第二,为工具栏增加UPDATE_COMMAND_UI机制,如果工具栏不需要为用户显示视觉反馈的话,那么就不需要第二部分了。但是,这种情况并不常见,通常还得必须支持UPDATE_COMMAND_UI_机制。
为对话框增加工具栏
第一步:使用Visual C++资源编辑器创建要加入对话框的工具栏资源
第二步:手工为对话框类加入一个CToolBar类型的成员变量
CToolBar m_wndToolBar;//对话框工具栏
第三步:在OnInitDialog()函数中,实现以下代码:
BOOL CDemoDlg::OnInitDialog()
{
CDialog::OnInitDialog();
//1、创建工具栏
if( !m_wndToolBar.Create(this) || !m_wndToolBar.LoadToolBar(IDR_DLG_TOOLBAR) )
{
TRACE0("Failed to create dialog toolbar/n");
EndDialog(IDCANCEL);
}
// 2 计算工具栏的大小
CRect rcClientStart;
CRect rcClientNow;
GetClientRect(rcClientStart);
RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0, reposQuery, rcClientNow);
//3、移动所有控件,从而在客户区内,这些控件位于 与没有控制条的情况下,在相同的位置。
CPoint ptOffset(rcClientNow.left - rcClientStart.left,rcClientNow.top - rcClientStart.top);
CRect rcChild;
CWnd* pwndChild = GetWindow(GW_CHILD);
while (pwndChild)
{
pwndChild->GetWindowRect(rcChild);
ScreenToClient(rcChild);
rcChild.OffsetRect(ptOffset);
pwndChild->MoveWindow(rcChild, FALSE);
pwndChild = pwndChild->GetNextWindow();
}
// 4 、调制窗口尺寸,为工具条腾出空间
CRect rcWindow;
GetWindowRect(rcWindow);
rcWindow.right += rcClientStart.Width() - rcClientNow.Width();
rcWindow.bottom += rcClientStart.Height() - rcClientNow.Height();
MoveWindow(rcWindow, FALSE);
// 5 、定位工具条
RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);
// 6 - 对话框居于屏幕中间
CenterWindow();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
第四步:在对话框类里手工增加与对话框按钮相关的WM_COMMAND_消息句柄。
具体实现步骤不详细说明了......