Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I make the ContextMenu appear only when clicked at certain portions of the Control?

You can listen to the Popup event, determine where the mouse was clicked and selectively make the menu items visible in the menu as follows:

private void contextMenu1_Popup( object sender, EventArgs e )
{
  // Get current mouse click position in the control
  // (assuming pictureBox1 is the control):
  Point ptClick = pictureBox1.PointToClient( Control.MousePosition );

  // Get the rectangle where you want to show the context menu.
  Rectangle preferredClickRect = new Rectangle( 0, 0, 50, 50 );
  if ( preferredClickRect.Contains( ptClick ) )
  {
    // Show all the menu items so that the menu will appear
    foreach ( MenuItem item in contextMenu1.MenuItems )
      item.Visible = true;
  }
  else
  {
    // Hide all the menu items so that the menu will not appear
    foreach ( MenuItem item in contextMenu1.MenuItems )
      item.Visible = false;
  }
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter