Anirudh Goel
Anirudh Goel

Reputation: 4721

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

Upvotes: 1

Views: 3401

Answers (3)

ChrisF
ChrisF

Reputation: 137178

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.

Upvotes: 0

Binary Worrier
Binary Worrier

Reputation: 51711

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.

Upvotes: 1

OregonGhost
OregonGhost

Reputation: 23759

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.

Upvotes: 2

Related Questions