Navigation Bar

30 August 2012

[ MFC ] - GetSystemMenu Example in VC++ for Accessing the Window's System Menu

1. Introduction

In this article, we will add our own command to the system menu of the dialog box. You can do the same for SDI as well as MDI applications. The system menu will appear when you click the top left corner of the window. Such system menu is shown below using the windows supplied notepad:

In our sample, we are going to add our system menu item to the dialog based application.

2. Code Explanation

First, a dialog based MFC application named SysCommand is created. Then, a command identifier is added to the resource.h file. The command identifier is given below:

//Sample 01: Add the Command Identifier
#define IDM_SYSCOMMAND_CUSTOM            32771

Next, in the CSysCommand class, the OnInitDialog function is modified so that it will get the system menu and adds our own menu item to it. To get the system menu GetSystemMenu function is called in the OnInitDialog. Once we have a menu, a menu item is added to it using AppendMenu function by supplying the command identifier that we added just now in the header file. Below is the code for it.

// TODO: Add extra initialization here
//Sample 02: Get System Menu and Add your own menu item
CMenu * pSystemMenu = GetSystemMenu(FALSE);
pSystemMenu->AppendMenu(0, IDM_SYSCOMMAND_CUSTOM, _T("Custom Menu"));

In the dialog class’s implementation file (.cpp), search for the function void CSysCommandDlg::OnSysCommand(UINT nID, LPARAM lParam). This function is the handler for all the system menu commands. To know the command source, the nID parameter is compared with the command identifier and once the ID matches the command is handled. In our sample, I just provided a message box. Below is the modified code:

void CSysCommandDlg::OnSysCommand(UINT nID, LPARAM lParam)
       if ((nID & 0xFFF0) == IDM_ABOUTBOX)
              CAboutDlg dlgAbout;
       //Sample 03: Check nID with your Resource Identifier for the
       //                  custom menu command.     
       else if(nID == IDM_SYSCOMMAND_CUSTOM)
              AfxMessageBox(_T("Your Custom System Command Invoked..."));
              CDialog::OnSysCommand(nID, lParam);

3. Running the Sample

Below specified video shows the sample in action.

Source Code : Download