在vs2010的MFC单文档中,创建带有图标的自定义工具栏,按钮和图片都没法显示。操作步骤如下:
1、头文件新增定义:
(1)
CMFCToolBarImages m_myImages; //图片列表
CMFCToolBar m_mywndToolBar;//自定义工具栏
(2)
afx_msg void OnToolBarButton(UINT nID);
2、源文件新增内容:
(1)
enum {
ID_LOGIN = 5000,
ID_LOGOUT,
ID_VIEW,
};
typedef struct SCustomizeButton
{
unsigned int id;
char name[64];
char tip[64];
}SCustomizeButton;
static SCustomizeButton CustomizeButton[]=
{
{ID_LOGIN, "login.bmp", "登陆"},
{ID_LOGOUT, "logout.bmp", "退出"},
{ID_VIEW, "view.bmp", "视图"}
};
(2)
ON_COMMAND_RANGE(ID_LOGIN, ID_VIEW, &CMainFrame::OnToolBarButton)
(3)将OnCreate修改如下:
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWndEx::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndStatusBar.Create(this))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT));
if (!m_mywndToolBar.CreateEx(this))
{
TRACE0("Failed to create tool bar\n");
return -1; // fail to create
}
m_mywndToolBar.SetSizes(CSize(31,30),CSize(24,24));
m_mywndToolBar.SetWindowText("mytoolbar");
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
DockPane(&m_mywndToolBar);
//设置图像大小
m_myImages.SetImageSize(CSize(24,24),FALSE);
int i = 0;
char tmp[32] = {0};
char strPath[MAX_PATH] = {0}, strFull[MAX_PATH] = {0};
int buttonNum = sizeof(CustomizeButton) / sizeof(CustomizeButton[0]);
HBITMAP hBitmap = NULL;
//获取文件路径并加载
GetModuleFileName(NULL, strPath, MAX_PATH);
(_tcsrchr(strPath,'\\'))[1] = 0;
for (i = 0; i < buttonNum; i++)
{
memset(strFull, 0, sizeof(strFull));
StrCpy(strFull, strPath);
StrCat(strFull, "\\");
StrCat(strFull, CustomizeButton[i].name);
hBitmap = (HBITMAP)LoadImage(AfxGetResourceHandle(), strFull, IMAGE_BITMAP, 0, 0, LR_DEFAULTCOLOR|LR_LOADFROMFILE);
m_myImages.AddImage(hBitmap);
}
//加载位图
m_mywndToolBar.SetUserImages(&m_myImages);
//创建工具条按钮及提示
for (i = 0; i < buttonNum; i++)
{
int index = 0;
//创建工具条按钮
m_mywndToolBar.InsertButton(CMFCToolBarButton(CustomizeButton[i].id, i, NULL, TRUE, 0));
//设置按钮提示
m_mywndToolBar.SetButtonText(i, CustomizeButton[i].tip);
}
return 0;
}
(4)
void CMainFrame::OnToolBarButton(UINT nID)
{
switch (nID)
{
case ID_LOGIN:
AfxMessageBox("login");
break;
case ID_LOGOUT:
AfxMessageBox("logout");
break;
case ID_VIEW:
AfxMessageBox("view");
break;
default:
AfxMessageBox("other");
break;
}
}
运行结果如下:
请各路大神帮忙指定啊。