C#:当链接到两个不同的对象时,如何检测谁是上下文菜单的菜单项的调用者?
我有两个标签,lblOn 和 lblOff。我将“一个”上下文菜单链接到两个标签以放弃必须制作两个相同的标签。
我将如何找出名为 contextmenu.menuitem 的标签对象?这样点击的 menuitem 就知道它的 contextmenu 是由 lblOn 标签还是 lblOffline 调用的?
C#:当链接到两个不同的对象时,如何检测谁是上下文菜单的菜单项的调用者?
我有两个标签,lblOn 和 lblOff。我将“一个”上下文菜单链接到两个标签以放弃必须制作两个相同的标签。
我将如何找出名为 contextmenu.menuitem 的标签对象?这样点击的 menuitem 就知道它的 contextmenu 是由 lblOn 标签还是 lblOffline 调用的?
检查. SourceControl
_ContextMenuStrip
漠视。在谷歌搜索了一下之后,我找到了一个解决方案+代码示例。
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);
}
}
}
}
}
来源: http ://www.tek-tips.com/viewthread.cfm?qid=1441041&page=8
我知道这是很久以前提出的一个问题,但我真的无法用代码找到一个简单的答案......我知道 SLaks 有点指出了这一点,但我认为那里的其他人需要一个代码示例......
我想知道谁调用了富文本框或标签之间的上下文菜单。原因是我只想要一个上下文菜单,并且如果调用者是富文本框且未选择任何内容,则希望禁用其中的复制按钮。
这是我的代码:
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;
}
}
用这个:
contextMenuStrip1.SourceControl;