Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

10. Windows Forms Menus

10.12 How do I control the position of the context menu when it is invoked via the keyboard?


Normally, the context menu will be shown at the center of the control when the keyboard is used to invoke the context menu of a control (Shift+F10, for example). You can customize the location as follows.

  1. Override WndProc in the grid and check if the Message.Msg is WM_CONTEXTMENU (0x007b)
  2. If so, check if the Message.LParam is -1, which means this was due to a keyboard message as opposed to the user right-clicking the mouse.
  3. Now, call the associated ContextMenu's Show method explicity at the selected row position.
  4. Make sure NOT to call the base class after showing the menu explicitly.


protected override void WndProc(ref Message m)
{
     if(m.Msg == 0x007B /*WM_CONTEXTMENU*/)
     {
          // LParam == -1 means that this is due to a keyboard message
          if((int)m.LParam == -1)
          {
               this.contextMenu.Show();
               return;
          }
     }
}



[VB.Net]
Protected Overrides Sub WndProc(ByRef m As Message)
     If m.Msg = 0x007B Then 'WM_CONTEXTMENU
          ' LParam == -1 means that this is due to a keyboard message
          If (CType(m.LParam,Integer)) = -1 Then
               Me.contextMenu.Show()
               Return
          End If
     End If
End Sub