C #: How to determine who is the caller of a context menu when it is associated with two different objects?

C #: how to determine who is the caller of a context menu if it is associated with two different objects?

I have two labels: lblOn and lblOff. I associate the "one" context menu with both labels to eliminate the need to make two of them.

How do I know which label object is called contextmenu.menuitem? Thus, clicking on menuitem knows if the context menu was caused by the label lblOn or lblOffline?

+4
source share
4 answers

Check the SourceControl ContextMenuStrip property.

+15
source

Ignoring After googling a little more, I found an example of a solution + code.

 private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { //Make sure the sender is a ToolStripMenuItem ToolStripMenuItem myItem = sender as ToolStripMenuItem; if (myItem != null) { //Get the ContextMenuString (owner of the ToolsStripMenuItem) ContextMenuStrip theStrip = myItem.Owner as ContextMenuStrip; if (theStrip != null) { //The SourceControl is the control that opened the contextmenustrip. //In my case it could be a linkLabel LinkLabel linkLabel = theStrip.SourceControl as LinkLabel; if (linkLabel == null) MessageBox.Show("Invalid item selected.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); else { if (MessageBox.Show(string.Format("Are you sure you want to remove BOL {0} from this Job?", linkLabel.Text), "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { linkLabel.Text = Program.NullValue(linkLabel); } } } } } 

Source: http://www.tek-tips.com/viewthread.cfm?qid=1441041&page=8

+6
source

I know this is a question many years ago, but I really could not find a simple answer with the code ... I know that SLaks pointed it out, but I think others need a code sample there ...

I wanted to know who brought up the context menu between a rich text box or shortcut. The reason is that I wanted only one context menu and wanted the copy button inside it to be disabled if the calling object was a rich text field in which nothing was selected.

Here is my code:

  private void contextMenuStrip1_Opened(object sender, EventArgs e) { //get the context menu (it holds the caller) ContextMenuStrip contextMenu = sender as ContextMenuStrip; //get the callers name for testing string controlName = contextMenu.SourceControl.Name; //test if it is infact me rich text editor making the call. if (controlName == "text_rchtxt") { //if I have nothing selected... I should not be able to copy if (text_rchtxt.SelectedText == "") copy_shrtct.Enabled = false; } else { //if I do have something selected or if its another control making the call, enable copying copy_shrtct.Enabled = true; } } 
+2
source

Use this one:

 contextMenuStrip1.SourceControl; 
-1
source

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


All Articles