C#:当链接到两个不同的对象时,如何检测谁是上下文菜单菜单项的调用者?
我有两个标签,lblOn和lblOff。我将“一个”上下文菜单链接到两个标签,以丢弃必须制作两个相同的标签。
我如何找出名为contextmenu.menuitem的标签对象?这样点击菜单项就知道是不是它的上下文菜单是由lblOn标签还是lblOffline调用的?
答案 0 :(得分:15)
检查SourceControl
的{{1}}属性。
答案 1 :(得分:6)
否认。谷歌搜索后,我找到了一个解决方案+代码示例。
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
答案 2 :(得分:2)
我知道这是许多月前的一个问题,但我真的找不到 一个简单的代码答案...... 我知道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;
}
}
答案 3 :(得分:-1)
使用它:
contextMenuStrip1.SourceControl;
样品:
using (MemoryStream ms = new MemoryStream())
{
Chart chartx = (Chart)stripChart.SourceControl;
chartx.SaveImage(ms, ChartImageFormat.Png);
Bitmap bm = new Bitmap(ms);
Clipboard.SetImage(bm);
}