views:

918

answers:

3

Hi, 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

+2  A: 

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.

OregonGhost
i tried the Opening Event, but what do i change in it? How do i Prevent it from Opening..
Anirudh Goel
You could start with reading the docs. The Opening event gets a CancelEventArgs parameter, where you have to set Cancel to true to cancel the opening.
OregonGhost
Set the CancelEventArgs.Cancel to true.
Ants
thanks i got it!
Anirudh Goel
+1  A: 

There is a work around.

Lets say Menu Item A sets the flag that controls the context menu on control B.

In the click event for A, you set b.ContextMenu = nothing to switch it off, and set b.ContextMenu back to the context menu control to switch it back on.

Binary Worrier
Sounds like a hack to me. That will make it really hard to maintain if you have more than one control that can popup the menu.
OregonGhost
A: 

In WinForms there's also the Click event - which does get fired for a right mouse click.

If you are using WPF you should have MouseRightButtonDown and MouseRightButtonUp events.

Check out the table on this MSDN page which lists which controls raise which click events. Significantly, Button, CheckBox, RichTextBox and RadioButton (and a few others) don't raise and event on right click.

ChrisF