打开记事本,打开任何一个常用软件,几乎都用工具栏和任务栏,很神秘吗?一点也不,跟我来,一起动手做
由于不能用Resource Edit绘制,要实现这两个控件,需要引用<CommCtrl.h>头文件和它的动态连接库,来手动创建
首先,加上头文件,加载动态连接库#pragma comment(lib,"comctl32.lib"),接着注册通用控件
typedef struct tagINITCOMMONCONTROLSEX
{
DWORD dwSize;
DWORD dwICC;
} INITCOMMONCONTROLSEX, *LPINITCOMMONCONTROLSEX;
其中,dwSize=sizoef(INITCOMMONCONTROLSEX)为该结构体的大小,
dwICC为需要从DLL中加载的控件类型,我们需要的是ICC_BAR_CLASSES,其中包括toolbar, status bar, trackbar, and ToolTip
然后,初始化
INITCOMMONCONTROLSEX InitCtrlEx;
InitCommonControlsEx(&InitCtrlEx);
再次,创建工具栏和任务栏
//创建状态栏
HWND hStatusBar;
hStatusBar=CreateWindowEx(0L, // extended styles
STATUSCLASSNAME, // status bar
NULL, // no text
WS_CHILD | WS_VISIBLE , // styles
0, 0, 0, 0, // x, y, cx, cy
hWnd, // parent window
(HMENU)100, // window ID
hInst, // instance
NULL); // window data
if( hStatusBar==NULL )
{
MessageBox(hWnd,L"Status Bar not created!",NULL,MB_ICONERROR);
return FALSE;
}
//创建工具栏
const int NUMBUTTONS =3;//工具栏上的按钮个数
TCHAR Caption[40]={0};
HWND hToolBar;
TBBUTTON tbb[]={
{ 0, IDM_EXIT, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0L, 0},
{ 0, 0, TBSTATE_ENABLED, TBSTYLE_SEP, 0L, -1},
{ 1, IDM_ABOUT, TBSTATE_ENABLED, TBSTYLE_BUTTON, 0L, 0}
};
/*TBBUTON为一个结构体,包含工具栏上按钮的信息
typedef struct _TBBUTTON
{
int iBitmap;
int idCommand;
BYTE fsState;
BYTE fsStyle;
#ifdef _WIN64
BYTE bReserved[6] // padding for alignment
#elif defined(_WIN32)
BYTE bReserved[2] // padding for alignment
#endif
DWORD_PTR dwData;
INT_PTR iString;
} TBBUTTON, NEAR *PTBBUTTON *LPTBBUTTON;
其中,
iBitmap(Zero-based index of the button image),
idCommand(Command identifier associated with the button),
fsState(Button state flags),
fsStyle(Button style),
dwData(Application-defined value),
iString(Zero-based index of the button string, or a pointer to a string buffer that contains text for the button. )
*/
TBADDBITMAP tbBitamps;
tbBitamps.hInst = hInst; // current instance
tbBitamps.nID = IDB_BITMAP_STANDARD;
//添加图片到工具栏按钮上
hToolBar=CreateWindowEx(0L, // no extended styles
TOOLBARCLASSNAME, // status bar
NULL, // no text
WS_CHILD | WS_VISIBLE , // styles
16, 16, 16, 16, // x, y, cx, cy
hWnd, // parent window
(HMENU)101, // window ID
hInst, // instance
NULL); // window data
if( hToolBar==NULL )
{
MessageBox(hWnd,L"Tool Bar not Created!",NULL,MB_ICONERROR);
return FALSE;
}
SendMessage(hToolBar, TB_ADDBITMAP, 0, (LPARAM)&tbBitamps); //添加图片到工具栏
SendMessage(hToolBar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0); //计算工具栏的大小
SendMessage(hToolBar, TB_ADDBUTTONS, (WPARAM)3, (LPARAM)(LPTBBUTTON)&tbb);//添加按钮到工具栏
还有种便捷的方法,但是微软已经不提倡使用了就是调用API函数
HWND CreateToolbarEx(
HWND hwnd,
DWORD ws,
UINT wID,
int nBitmaps,
HINSTANCE hBMInst,
UINT_PTR wBMID,
LPCTBBUTTON lpButtons,
int iNumButtons,
int dxButton,
int dyButton,
int dxBitmap,
int dyBitmap,
UINT uStructSize
);
具体的情查阅MSDN