65.9K
CodeProject is changing. Read more.
Home

VB.NET/WinForms: Add MenuItem to SystemMenu

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Dec 13, 2022

CPOL
viewsIcon

9709

downloadIcon

107

Adding ContextMenu's MenuItem to the SystemMenu of Form in Windows Forms Application

Introduction

Why do we need to use MenuItem for adding to SystemMenu?
A MenuItem has own Event and is easy to use for invoking our Command statements.

Background

Using API Functions for Add MenuItem to SystemMenu: GetSystemMenu API Function to take Handle of Form's SystemMenu - GetMenuItemID API Function to take ContextMenu's MenuItem ID and InsertMenu API Function to Insert MenuItem at SystemMenu.

Using the Code

Use API Functions at General Declarations of Form

GetSystemMenu API Function

Declare Function GetSystemMenu Lib "user32" Alias "GetSystemMenu" (
  ByVal hwnd As Long,
  ByVal bRevert As Boolean) As Long 

GetMenuItemID API Function

 Declare Function GetMenuItemID Lib "user32" (
                   hMenu As Long,
                   nPos As Integer) As Integer

InsertMenu API Function

 Declare Function InsertMenu Lib "user32" Alias "InsertMenuA" (
    ByVal hMenu As Long,
    ByVal nPosition As Long,
    ByVal wFlags As Long,
    ByVal wIDNewItem As Long,
    ByVal lpNewItem As String) As Long

You need to add a ContextMenu component to your Form at first:

Make a new MenuItem (e.g., About MenuItem):

Then, add an 'About Box' to the project:

To take SystemMenu's Handle of the Form:

Dim SysMenu As Long = GetSystemMenu(Me.Handle.ToInt64, False) 

Take MenuItem ID:

Dim hMenuItem As Long = GetMenuItemID(MenuItem1.Parent.Handle.ToInt64, MenuItem1.Index) 

Insert MenuItem to Form's SystemMenu:

InsertMenu(SysMenu, 0, &H0&, hMenuItem, MenuItem1.Text) 

Add the above statements to the Form's Load Event:

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      Dim SysMenu As Long = GetSystemMenu(Me.Handle.ToInt64, False)
      Dim hMenuItem As Long = _
          GetMenuItemID(MenuItem1.Parent.Handle.ToInt64, MenuItem1.Index)
      InsertMenu(SysMenu, 0, &H0&, hMenuItem, MenuItem1.Text)
    End Sub 

Double click on ContextMenu's MenuItem to write Command statements as below:

    Private Sub MenuItem1_Click(sender As Object, e As EventArgs) Handles MenuItem1.Click
      Dim AboutBox As New AboutBox1
      AboutBox.Show(Me)
    End Sub 

History

  • 13th December, 2022: Initial version