"Windows Programming" series seventh: creation and use of menubar

Source: Internet
Author: User



Previous we learned to use the Windows API to create toolbars and menu bars, closely related to the previous article is the menu bar, the menu bar is an integral part of most complex Windows applications. For example, Windows comes with a Notepad menu bar:

The menu is usually under the title bar, above the toolbar, often called the main menu or the top-level menu (Top-level menu), the top-level menu may also have a pop-up menu (popup menus) or a submenu (submenu). The pop-up menu also has a "checked" (checked) status, and the menu also has a enabled, disabled status.

Each menu has an ID corresponding to it, and when a menu is clicked, the program passes the menu ID to the message handler function in the WM_COMMAND message to know which menu is being pressed.

The most common creation of a menu bar is to take advantage of the VS Menu resource editor and then load the resource. For example, the following code snippet uses the LoadMenu function to load menu resource edit menus when creating the main form:

HMenu = LoadMenu (hinstance, Makeintresource (Id_menu)), hWnd = CreateWindow (Text ("MyClass"), Text ("MyTitle"), Ws_ Overlappendwindow, Cw_usedefault, cw_usedefault, +, NULL, HMenu, HINSTANCE, NULL);


Another way to do this is to call the SetMenu function to set the menu in the process wm_create message:

SetMenu (HWnd, HMenu);


This article has been adhering to the principle of using an API to create rather than resources. Because using the API to create a bit of a hassle, but more independent, such as if not with the VS environment, there may be no resource editing, if our source program in a non-vs environment can be compiled to show the universality and portability.

    • Menu message

When a user chooses a menu, wm_initmenu messages and Wm_menuselect,wm_initmenu messages are generated, giving us the opportunity to do something before the menu is selected, and wm_ The MenuSelect message is sent when the menu is selected or when the cursor is moved to the menu, and we can use this message to handle the menu when it is selected.

Wm_initmenupopup messages are sent before a pop-up menu is displayed and can be used to modify some menu displays.

The most important and common is the WM_COMMAND message we mentioned above, which is generated when the menu is clicked. Please refer to MSDN for the parameter meaning of the above message.

    • Menu creation

There are dozens of menu-related APIs, we use only a few common API functions, these functions can basically complete the basic functions of the menu, more menu functions and functions, please refer to MSDN.

function CreateMenu can create a menu, CreatePopupMenu create a drop-down or popup is a menu. Function AppendMenu can append a menu item, function InsertMenu can insert a menu item, TrackPopupMenu function will display a pop-up menu at the specified location. These menu prototypes are as follows:

HMENU CreateMenu (VOID); HMENU CreatePopupMenu (VOID); BOOL AppendMenu (HMENU HMENU, UINT uflags, Uint_ptr Uidnewitem, LPCTSTR lpnewitem); BOOL InsertMenu (HMENU HMENU, uint uposition, uint uflags, PTR Uidnewitem, LPCTSTR lpnewitem); BOOL TrackPopupMenu (HMENU HMENU, UINT uflags, int x, int y, int nreserved, HWND hwnd, HWND prcrect);


In fact, most of the common parts of the menu is done with these functions, not complex. Without saying, directly on the side of the code side to explain more directly, we use these common functions to create and use the menus using the following demo demo:

#include <windows.h> #define IDM_FILE_NEW 1001#define idm_file_open 1002#define idm_file_save 1003#define Idm_edi T_copy 1004#define idm_edit_paste 1005#define idm_edit_hl 1006#define idm_view_full 1007#define IDM_VIEW_HALF 1008#d Efine idm_view_part 1009#define idm_file_open_solution 10021#define idm_file_open_project 10022static TCHAR szAppName[ ] = TEXT ("Menubar"), Static LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain (hinstance hinstance, H     INSTANCE 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;            } hWnd = CreateWindow (szappname,//window class name Szappname,        Window caption Ws_overlappedwindow,//window style cw_usedefault,                          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;}     HMENU Createmenubar (void) {//Total menu HMENU HMENU = CreateMenu ();     File menu HMENU Hfilemenu = CreateMenu ();     AppendMenu (Hfilemenu, mf_string, Idm_file_new, TEXT ("&new")); AppendMenu (Hfilemenu, Mf_separator, 0, NULL);     Insert a bar, see the effect AppendMenu (Hfilemenu, mf_string, Idm_file_save, TEXT ("&save"));     AppendMenu (HMenu, Mf_popup, (uint_ptr) Hfilemenu, TEXT ("File (&f)");     The file's Level two submenu HMENU Hsubmenu = CreateMenu ();     AppendMenu (Hsubmenu, mf_string, Idm_file_open_solution, TEXT ("so&lution"));     AppendMenu (Hsubmenu, mf_string, Idm_file_open_project, TEXT ("Pro&ject")); Insert the level two menu into the second position insertmenu (Hfilemenu, 1, mf_byposition|     Mf_popup, (uint_ptr) Hsubmenu, TEXT ("Open"));     Edit menu Hfilemenu = CreateMenu (); AppendMenu (Hfilemenu, mf_string, Idm_ediT_copy, TEXT ("&copy"));     AppendMenu (Hfilemenu, mf_string, Idm_edit_paste, TEXT ("&paste"));     AppendMenu (Hfilemenu, Mf_separator, 0, NULL); AppendMenu (Hfilemenu, mf_string| mf_checked, Idm_edit_hl, text ("&update"));//Add a check option AppendMenu (HMenu, Mf_popup, (uint_ptr) Hfilemenu, Text ("     Edit (&e));     Zoom Menu Hfilemenu = CreateMenu ();     AppendMenu (Hfilemenu, mf_string, Idm_view_half, TEXT ("&half"));     AppendMenu (Hfilemenu, Mf_separator, 0, NULL); Sets a grayed out menu that can be modified with the EnableMenuItem function AppendMenu (Hfilemenu, mf_string|     Mf_grayed, Idm_view_part, TEXT ("P&art"));     AppendMenu (HMenu, Mf_popup, (uint_ptr) Hfilemenu, TEXT ("Zoom (&z)")); return hMenu;}     Static LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM WPARAM, LPARAM LPARAM) {HDC hdc;     Paintstruct PS;               Switch (message) {case wm_create: {HMENU HMENU = Createmenubar (); SetMenu (HWnd, HMenu);     The above just creates a menu that needs to be set     } return 0;               Case Wm_rbuttonup: {point point;               Point.x = LoWord (LParam);               Point.y = HiWord (LParam); ClientToScreen (HWnd, &point); The coordinates here are relative to the screen and need to be converted to customer coordinates HMENU hsubmenu = GetSubMenu (GetMenu (hWnd), 0);          Gets the No. 0 submenu of the menu, using this menu to demonstrate the popup menu TrackPopupMenu (Hsubmenu, Tpm_rightbutton, Point.x, Point.y, 0, HWnd, NULL);     } return 0; Case Wm_command:switch (LoWord (WParam)) {case Idm_file_new:messagebo                    X (hWnd, Text ("You click New File button"), TEXT ("hint"), MB_OK);               Break          Default:break;     } 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 running this demo, click on the "File" menu below:

Click on the "Edit" menu below:


right mouse button popup shortcut menu:

This article only demonstrates common menus, other things like bitmap menus, non-client area pop-up menus, and more are interesting to discuss, or you can refer to MSDN's related functions to test for yourself. The menu bar programming of this article combines the contents of the previous toolbar and the status bar, and the second section of creating a common control, which basically completes the interface programming of the window application. Again, of course, we are all based on the Windows API functions, and many people may say that I use MFC, the Resource Editor, the Control Panel under the dialog box, and even VB, C # can quickly write these interfaces. Yes, but hiding underneath these is still going back to our basic API.


Focus on the public platform: 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 the basics of programming and solve programming problems. Programmer Interactive Alliance , developer's own home.

Reprint Please indicate the source http://www.coderonline.net/ , thank you for your cooperation!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Windows Programming" series seventh: creation and use of menubar

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.