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

Platform: WinForms| Category: Menus

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:


		// In C#
		private void contextMenu1_Popup(object sender, System.EventArgs e)
		{
			// Get current mouse click position in the control (assuming pictureBox1 is the control):
			Point ptClick = this.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 this.contextMenu1.MenuItems)
					item.Visible = true;
			}
			else
			{
				// Hide all the menu items so that the menu will not appear
				foreach(MenuItem item in this.contextMenu1.MenuItems)
					item.Visible = false;
			}
		}

		’ In VB.Net
		Private  Sub contextMenu1_Popup(ByVal sender As Object, ByVal e As System.EventArgs)
			’ Get current mouse click position in the control (assuming pictureBox1 is the control):
			Dim ptClick As Point =  Me.pictureBox1.PointToClient(Control.MousePosition) 
			’ Get the rectangle where you want to show the context menu.
			Dim preferredClickRect As Rectangle =  New Rectangle(0,0,50,50) 
			If preferredClickRect.Contains(ptClick) Then
				’ Show all the menu items so that the menu will appear
				Dim item As MenuItem
				For Each item In Me.contextMenu1.MenuItems
					item.Visible = True
				Next
			Else 
				’ Hide all the menu items so that the menu will not appear
				Dim item As MenuItem
				For Each item In Me.contextMenu1.MenuItems
					item.Visible = False
				Next
			End If
		End Sub

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.