"Windows Programming" series sixth: Creating Toolbar and StatusBar

Source: Internet
Author: User

In the previous article we learned how to use Windows GDI paint, the application is a static window of light, we use the Windows application, any slightly more complex program will have the toolbar and the status bar, the toolbar is mainly used for some quick function buttons. For example, a typical Windows application is the menu bar, from the menu bar we can choose the various functions provided by the application, but some features are more commonly used, and can not be placed in the first level of the menu, you need to go to level two, three or more menus to choose. Obviously this is more cumbersome to use, so this time the role of the toolbar is reflected, the General toolbar is located below the menu bar, but located on the top of the customer window. Here is the toolbar for the text editor for Windows:

StatusBar is mainly used to show the operation status of the application, statistical information, operation information and other prompts, generally read-only status. The typical status bar is placed at the bottom of the window, such as the following is the status bar of the Word application I'm using:

What we're going to learn together this time is to create a basic status bar and menu bar using pure Windows API functions. If the properties of MFC's friends know, it is easy to use MFC to make toolbars and menu bars. But the use of pure API is a bit of a hassle, of course, the feeling is not the same, such as to create dynamically, using MFC's Resource editor is powerless, but for the way we use today's API creation, it shows his strong.

First of all, let's talk about the creation of common Windows controls, and we know that all control creation with Windows is actually called CreateWindow or CreateWindowEx from windows (see CreateWindowEx for example) for these two functions , of course today's menu bar and status bar need both functions to create. Because both the toolbar and the status bar are controls in the Universal control group for Windows, there is a default class name. When you create a toolbar, the class name is Toolbarclassname, and when you create the status bar, the class name is Statusclassname, and the two macros are defined in the Commctrl.h file according to whether the Unicode encoding is "TOOLBARWINDOW32" and " Msctls_statusbar32 "for the wide character version and the ANSI version.

    • Creating toolbars

In addition to using CreateWindowEx to create a good toolbar, as a better view, we can also give the toolbar spike as well as feature hints. The most convenient way to add icons is to use some column image list APIs to load and manage the toolbars ' pictures. Imagelist_create can create a picture list, which is prototyped as:

Himagelist imagelist_create (int cx, int CY, UINT flags,  int cinitial, int cgrow);

The function usage is more clearly stated on MSDN. This list is created with no pictures, just a list-managed container, and a picture collection needs to be loaded. The API required to add images is as follows:

int imagelist_addmasked (himagelist himl, Hbitmap hbmimage, Colorref crmask);

After the picture is loaded, you can also set the display properties of the picture, including displaying pictures, text, and informational cues. The response of the tool button is implemented by sending a WM_COMMAND message to the window handler, with the user handling the button event. The ToolTip for the toolbar is indicated by the WM_NOTIFY message, which is set by the user, and the creation of the toolbar is provided in the following example.

    • Create a status bar

The installation status bar is much simpler than the toolbar, with CreateWindowEx to establish the status bar, by default, the status bar has only one display panel (panel), to create multiple panels, just to the status bar to configure the length of a panel to send sb_setparts messages, The message parameters are the number of panels and the array of endpoints of the panel. Like what:

int array[3]={120,120*2,-1}; SendMessage (Hwndstatus,sb_setparts, (WPARAM) 3, (LPARAM) array);

Indicates that the status bar panel is divided into 3 parts, the first part to 120 pixels, the second to 240 pixels, and the remaining (-1) in the third part.

Set the panel text content, you can send a sb_settext message to the status bar, to add a small icon in the status bar panel, you can send a SB_SETICON message to the status.

The above toolbar and status bar are just the basics, and more settings and message handling are available on MSDN. This series focuses on basic programming and use, but only introduces common usage, but these usages are also enough for beginners to use.

    • Working with instances

Below, we show you how to create, use the toolbars and the status bar using the pure Windows API using a basic instance program. Toolbar created in the program has three icons, when the program is displayed properly, the mouse moves on a toolbar button, or in the disable state, there will be different picture display, readers can change their own other favorite icons.

#include <windows.h> #include <commctrl.h> #include <tchar.h> #pragma comment (lib, "Comctl32.lib")// Windows XP sytle button#pragma COMMENT (linker, "\"/manifestdependency:type= ' Win32 ' "" Name= " Microsoft.windows.common-controls ' "" version= ' 6.0.0.0 ' processorarchitecture= ' * ' "" publickeytoken= " 6595B64144CCF1DF ' language= ' * ' "") #define Idc_toolbar 1001#define idc_statusbar 1002//#define Pic_resource_used# ifdef pic_resource_used#define idb_new 110#define idb_open 111#define idb_save 112#endif#define ID_FOPEN 1111#define Id_fclose 1112#define id_fsave 1113static TCHAR szappname[] = TEXT ("toolbar"); static LRESULT CALLBACK WndProc (HWND, UINT      , WPARAM, LPARAM); int WINAPI WinMain (hinstance hinstance, hinstance hprevinstance, PSTR szcmdline, int icmdshow) {HWND     HWnd;     MSG msg;     Wndclass Wndclass; Wndclass.style = Cs_hredraw |     Cs_vredraw;     Wndclass.lpfnwndproc = WndProc;     Wndclass.cbclsextra = 0;     Wndclass.cbwndextra = 0; WndClass.hinstance = hinstance;     Wndclass.hicon = LoadIcon (NULL, idi_application);     Wndclass.hcursor = LoadCursor (NULL, Idc_arrow);     Wndclass.hbrbackground = (hbrush) getstockobject (White_brush);     Wndclass.lpszmenuname = NULL;     Wndclass.lpszclassname = Szappname; if (! RegisterClass (&wndclass)) {MessageBox (NULL, TEXT ("This program requires Windows nt!"), Szappname, Mb_ic          ONERROR);     return 0;     }//Initialize public space initcommoncontrolsex ICC;     icc.dwsize = sizeof (initcommoncontrolsex);     ICC.DWICC = icc_bar_classes;     Initcommoncontrolsex (&AMP;ICC); HWnd = CreateWindow (szappname,//window class name Szappname,/ /Window caption Ws_overlappedwindow,//window style Cw_usedefau                  LT,//initial x position cw_usedefault,//initial y position        ×,//initial x size,//initial y size  NULL,//parent window handle NULL,//window Menu handle HINSTANCE,//program instance handle NULL                     );     Creation Parameters ShowWindow (hWnd, icmdshow);          UpdateWindow (HWND);          while (GetMessage (&msg, NULL, 0, 0)) {translatemessage (&msg);     DispatchMessage (&AMP;MSG); } return Msg.wparam;}    HWND Createtoolbar (HWND Hparentwnd) {hwnd HWNDTB;    Tbbutton Tbb[3];    Himagelist himagelist,hhotimagelist,hdisableimagelist;    Hbitmap Hbitmap;    HInstance HInst = GetModuleHandle (NULL); Create Toolbar Control HWNDTB = CreateWindowEx (0, Toolbarclassname,text (""), ws_child| ws_visible| ws_border| Tbstyle_list| tbstyle_autosize| Tbstyle_tooltips,0,0,0,0,hparentwnd, (hmenU) idc_toolbar,hinst,null);    if (!HWNDTB) {return NULL;    } SendMessage (HWNDTB, Tb_buttonstructsize, (WPARAM) sizeof (Tbbutton), 0); The following creates a list of three 24x24 pixel-sized bitmap images for the toolbar icon himagelist = imagelist_create (24,24,ilc_color24| ilc_mask,3,1); #ifdef pic_resource_used hbitmap = LoadBitmap (HInst, Makeintresource (Idb_color3)); #else hbitmap = (HBI TMAP) LoadImage (NULL, TEXT ("Color24x3.bmp"), Image_bitmap, 0, 0, lr_loadfromfile| Lr_createdibsection);    Load a set of pictures #endif imagelist_addmasked (himagelist, Hbitmap, RGB (255,255,255));    DeleteObject (HBITMAP); SendMessage (hwndtb,tb_setimagelist,0, (LPARAM) himagelist); Image list when normal display hhotimagelist = Imagelist_create (24,24,ilc_color24| ilc_mask,3,1); #ifdef pic_resource_used hbitmap = LoadBitmap (Hinst,makeintresource (Idb_green3)); #else    Hbitmap = (hbitmap) loadimage (NULL, TEXT ("Green24x3.bmp"), Image_bitmap, 0, 0, lr_loadfromfile|    lr_createdibsection); #endif imagelist_addmasked (Hhotimagelist,hbitmap, RGB (255,255,255)); DelEteobject (HBITMAP); SendMessage (hwndtb,tb_sethotimagelist,0, (LPARAM) hhotimagelist); Mouse hover image List hdisableimagelist = Imagelist_create (24,24,ilc_color24| ilc_mask,3,1); #ifdef pic_resource_used hbitmap = LoadBitmap (Hinst,makeintresource (IDB_GRAY3)); #else    Hbitmap = (hbitmap) loadimage (NULL, TEXT ("Gray24x3.bmp"), Image_bitmap, 0, 0, lr_loadfromfile|    lr_createdibsection); #endif imagelist_addmasked (Hdisableimagelist,hbitmap, RGB (255,255,255));    DeleteObject (HBITMAP); SendMessage (hwndtb,tb_setdisabledimagelist,0, (LPARAM) hdisableimagelist);    When the toolbar button is lost, the image list ZeroMemory (TBB, sizeof);    Tbb[0].ibitmap =makelong (0,0);    Tbb[0].fsstate = tbstate_enabled; Tbb[0].fsstyle = tbstyle_button|    Btns_autosize;     Tbb[0].idcommand = Id_fopen;    tbb[0].istring = (INT_PTR) TEXT ("open");    Tbb[1].ibitmap =makelong (1,0);    Tbb[1].fsstate = tbstate_enabled; Tbb[1].fsstyle = tbstyle_button|    Btns_autosize;     Tbb[1].idcommand = Id_fclose; Tbb[1].istring = (int_ptR) TEXT ("Off");    Tbb[2].ibitmap =makelong (2,0);    Tbb[2].fsstate = tbstate_enabled; Tbb[2].fsstyle = tbstyle_button|    Btns_autosize;    Tbb[2].idcommand = Id_fsave;    tbb[2].istring = (INT_PTR) TEXT ("Save"); SendMessage (HWNDTB, tb_addbuttons, sizeof (TBB)/sizeof (Tbbutton), (LPARAM) &AMP;TBB);    Configure the toolbar button information SendMessage (hwndtb,wm_size,0,0); return HWNDTB;}    HWND Createstatusbar (hwnd hparentwnd) {#define PANEL_NUM 3 int array[panel_num]={120,120*2,-1};    HInstance HInst = GetModuleHandle (NULL); Create StatusBar control HWND hwndstatus = CreateWindowEx (0, Statusclassname, TEXT (""), ws_child| ws_border|    ws_visible, 0, 0, 0, 0, Hparentwnd, (HMENU) Idc_statusbar, HInst, NULL); if (hwndstatus) {SendMessage (Hwndstatus,sb_setparts, (WPARAM) Panel_num, (LPARAM) array);//Set Number of panels Sendmessa GE (Hwndstatus,sb_settext, (LPARAM) 1, (WPARAM) TEXT ("Panel-1")); Set the second panel content SendMessage (Hwndstatus,sb_settext, (LPARAM) 2, (WPARAM) TEXT ("Panel-2")); Set the third panel content} #undef panel_num return hwnDstatus;}    Static LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM WPARAM, LPARAM LPARAM) {HDC hdc;    Paintstruct PS;    Static HWND Htoolbar;    Static HWND Hstatusbar;        Switch (message) {Case Wm_create:htoolbar = Createtoolbar (hWnd);        Hstatusbar = Createstatusbar (hWnd);    return 0;        Case WM_COMMAND: {int wmid = LOWORD (WParam);        int wmevent = HiWord (WParam); Analysis Menu selection: switch (wmid) {case id_fopen:sendmessage (Htoolbar, Tb_enablebutton, (WPARAM) I            D_fopen, (LPARAM) Makelong (false,0));            SendMessage (Htoolbar, Tb_enablebutton, (WPARAM) Id_fsave, (LPARAM) Makelong (true,0));        Break            Case Id_fsave:sendmessage (Htoolbar, Tb_enablebutton, (WPARAM) Id_fsave, (LPARAM) Makelong (false,0));            SendMessage (Htoolbar, Tb_enablebutton, (WPARAM) Id_fopen, (LPARAM) Makelong (true,0));        Break Case Id_fclose:messagebox (HWnd, TEXT ("CLIck! "), TEXT (" hint "), MB_OK);        Break    }} return 0;        Case WM_NOTIFY: {lpnmhdr lpnmhdr= (LPNMHDR) LParam;        Lptooltiptext Lpttext;            if (lpnmhdr->code==ttn_getdispinfo) {         //Handling text tips when hovering the mouse over a toolbar            lpttext= (Lptooltiptext) LParam;                Switch (lpttext->hdr.idfrom) {case Id_fopen:lpttext->lpsztext=text ("Open file");            Break                Case Id_fclose:lpttext->lpsztext=text ("Close file");            Break                Case Id_fsave:lpttext->lpsztext=text ("Save as File");            Break    }}} return 0;        Case wm_size: {SendMessage (Htoolbar, tb_autosize, 0, 0);     SendMessage (Hstatusbar, wm_size, 0, 0);    } return 0;        Case Wm_mousemove: {TCHAR Szbuf[max_path];      _stprintf (Szbuf,text ("Mouse (%d,%d)"), LoWord (LParam), HiWord (LParam));  SendMessage (Hstatusbar, Sb_settext, 0, (LPARAM) (LPSTR) szbuf);    } return 0;        Case WM_PAINT:HDC = BeginPaint (hWnd, &ps);        ;        EndPaint (HWnd, &ps);    return 0;        Case Wm_destroy:postquitmessage (0);    return 0; } return DefWindowProc (hWnd, message, WParam, LParam);}

After the instance program, the results are shown as:

After pressing the "open" button on the program's toolbar, it becomes the disable state after you click "Save" and the "open" button will be activated again. As you can see, when you move the mouse over the Save button, a text prompt that prompts "Save as file" appears.

There are three panels in the status bar, the next two statically assigning strings at creation time, and the first one captures the mouse coordinates in the client area and displays them in real time.

In general, the basic usage of the toolbar and the status bar is relatively simple, just because the two controls belong to Microsoft's generic control, you need to call Initcommoncontrolsex to initialize the common control library and set the control you want to use before creating it. This article is written here, and interested readers should continue to follow the Windows Programming Basics series.

Focus on the public platform: the Programmer Interaction Alliance (coder_online), you can get the first original technical articles, and (Java/c/c++/android/windows/linux) technology Daniel Friends, online communication programming experience, get programming basics, Solve programming problems. Programmer Interactive Alliance, Developer's own home.

Reproduced please specify the source, thank you for your cooperation!

"Windows Programming" series sixth: Creating Toolbar and StatusBar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.