在 Windows 窗体上,我有 PictureBoxes
,每个都有一个 StripMenu
项。 PictureBoxes
位于一个单独的类中。当用户单击 StripMenuItem
时,我如何确定单击的是哪个 PictureBox
?
我看过有关对发件人执行某些操作的帖子,但我在属性中看不到与单击的项目相关的任何内容。
这是我的基本代码:
public Form1()
{
InitializeComponent();
ContextMenu cm = new ContextMenu();
MenuItem mi = new MenuItem()
{
Text = "click me"
};
mi.Click += new EventHandler(mi_Click);
cm.MenuItems.Add(mi);
Data d1 = new Data();
d1.px.Location = new Point(30, 30);
d1.px.ContextMenu = cm;
Data d2 = new Data();
d2.px.Location = new Point(100, 100);
d2.px.ContextMenu = cm;
Controls.Add(d1.px);
Controls.Add(d2.px);
}
void mi_Click(object sender, EventArgs e)
{
var s = sender;
}
class Data
{
public PictureBox px = new PictureBox
{
Size = new Size(40, 40),
BackColor = Color.Red
};
}
很抱歉,如果这个问题已经被问过,但我不知道如何搜索答案。
提前致谢
最佳答案
我已经有一段时间没有进行任何 Winforms 编码了 - 但您也许可以使用以下代码找出哪个控件导致了点击:
void mi_Click(object sender, EventArgs e)
{
// try to convert your "sender" to a ToolStripItem
ToolStripItem item = (sender as ToolStripItem);
if (item != null)
{
// if successful - get the MenuItem's "Parent" -> that should be your "ContextMenu"
ContextMenuStrip ctxMenu = item.Owner as ContextMenuStrip;
if(ctxMenu != null)
{
// if that's successful, the context menu's "SourceControl"
// should tell you which control the menu was opened over
Control controlThatCausedMenuItemToBeClicked = ctxMenu.SourceControl;
string controlsName = controlThatCausedMenuItemToBeClicked.Name;
}
}
}
更新: @Mesko 正确获取了 ToolStripItem
和 ContextMenuStrip
的类名 - 我有点生疏,不知道这些心不再 – 更新了我的帖子,感谢@Mesko。
但在最后一步,您取回了打开上下文菜单的控件,并且单击了菜单项。这是一个“通用”控件,但您始终可以获取该控件的 .Name
,然后根据名称将各个 PictureBox
分开。
关于c# - 如何判断点击事件在哪里触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20734029/