C # Mouse right click and focus control

I have a form in which users can add controls, and when they right-click, a context menu appears in which it is possible to display the properties of the control they clicked on. The problem I am facing is to decide how to determine what the user controls by right-clicking, as this can be any number of them, and then setting this control on the form. Does anyone have any good suggestions? Should I just use the (Sender object) part of the mouse event?

Thanks.

+3
source share
2 answers

My choice will use the object Sendermost straightforward. Although you need to do a casting if you want to have operations on a specific type of control.

UPDATE:

If you have a good naming convention, or at least for those form controls that need ContextMenu operations, here's how you can do it:

Attaching a mouse click event to specific controls or you can write something to attach all controls by iterating through a collection Controls.

label1.MouseClick += new MouseEventHandler(control_RightMouseClick);
label2.MouseClick += new MouseEventHandler(control_RightMouseClick);
label3.MouseClick += new MouseEventHandler(control_RightMouseClick);

Then perform various operations or show a different context menu for different controls.

void control_RightMouseClick(object sender, MouseEventArgs e)
{
    if (e.Button != MouseButtons.Right)
    {
        return;
    }
    if (sender.GetType().IsSubclassOf(typeof(Control)))
    {
        Control formControl = (Control)sender;
        switch (formControl.Name)
        {
            case "label_1":
                //do something
                contextMenuStrip1.Show(formControl, e.Location);
                break;
            case "label_2":
                //do something else
                contextMenuStrip2.Show(formControl, e.Location);
                break;
            case "label_3":
                //do something else
                contextMenuStrip3.Show(formControl, e.Location);
                break;
            case "panel_1":
                //do something else
                break;
            default:
                //do something else or return or show default context menu
                contextMenuStrip_default.Show(formControl, e.Location);
                break;
        }
    }

    return;
}
+5
source

You can either check the type of control that triggers the event using:

if (typeof(sender) == _control1.GetType())
{
     // ...
}

Tag . Tag , (un) . , , .

0

Source: https://habr.com/ru/post/1721610/


All Articles