My choice will be using object Sender
, most straight forward. Though you need to do casting if you want to have operations on the specific control type.
UPDATE:
If you have a good naming convention or at least for those form controls which need ContextMenu operations, here's how you can do it:
Attaching mouse click event to specific controls or you can write something to attach to all controls by iteration through the form's Controls
collection.
label1.MouseClick += new MouseEventHandler(control_RightMouseClick);
label2.MouseClick += new MouseEventHandler(control_RightMouseClick);
label3.MouseClick += new MouseEventHandler(control_RightMouseClick);
Then perform different operations or show 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;
}