Search code examples
c#user-controlsmouseclick-eventright-mouse-button

Explicitly Prevent ContextMenuStrip from Loading in C#


I have a requirement to hide the contextmenustrip when a particular flag is not set. As i don't think we can explicitly control the show/hide of the context menu strip, i decided to trap the right mouse button click on the control with which the contextmenustrip is associated. It is a UserControl, so i tried handling it's MouseClick event inside which i check if the flag is set and if the button is a right button. However to my amazement, the event doesn't get fired upon Mouse Right Click, but fires only for Left Click.

Is there any thing wrong with me or is there any workaround?

RIGHT CLICK IS GETTING DETECTED, Question TITLE and Description Changed

After Doing some more research, i got the rightclick to fire, when i Handled the Mouse_Down Event on the Control. However Am still clueless, as how to explicitly prevent the ContextMenuStrip From Loading. Another question being, why MouseClick didn't detect Right Button Click?


Current WorkAround

Registering the event handler

   userControl1.Control1.MouseDown += new MouseEventHandler(Control1_MouseDown);

 void Control1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right && flag == false)
        {
           userControl1.Control1.ContextMenuStrip = null;
        }
        else
        {
            userControl1.Control1.ContextMenuStrip = contextMenuStrip1;
        }

    }

this is the current workaround i'm doing. But how can i change it in the Opening Event of the ContextMenuStrip


Solution

  • Your solution will fail anyway when the context menu is invoked with the context menu key (or what it's called) on the keyboard. You can use the Opening event to cancel the opening of a context menu.