Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Basic

VB.NET/WinForms: Add MenuItem to SystemMenu

5.00/5 (2 votes)
13 Dec 2022CPOL 9.7K   107  
Adding ContextMenu's MenuItem to the SystemMenu of Form in Windows Forms Application
Create ContextMenu's MenuItem and put that to Form's SystemMenu by API Functions (GetSystemMenu, GetMenuItemID, InsertMenu)

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.

Image 1

Using the Code

Use API Functions at General Declarations of Form

GetSystemMenu API Function

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

GetMenuItemID API Function

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

InsertMenu API Function

VB
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:

Image 2

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

Image 3

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

Image 4

To take SystemMenu's Handle of the Form:

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

Take MenuItem ID:

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

Insert MenuItem to Form's SystemMenu:

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

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

VB
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:

VB
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)