如何确定哪个控件激活了上下文菜单?
在 C# winforms 应用程序中,我已将相同的上下文菜单分配给四个 PictureBox 控件。
我想确定哪个用于激活上下文菜单。
我在给定菜单项的 Click 事件中执行了以下操作,这看起来很尴尬:
MenuItem_Click(object sender, EventArgs e)
{
PictureBox Origin = (PictureBox)sender;
switch (Origin.Name)
{
case "pbOne":
// do something with #1
break;
case "pbTwo":
// do something with #2
break;
}
}
使用控件名称是感觉很尴尬的部分。
你能建议一个更好的方法吗?
编辑:
将sender
投射到PictureBox不起作用,因为我忘记了菜单项将是发送者,而不是PictureBox。所以我将不得不进一步回溯。
In a C# winforms app, I've assigned the same contextual menu to four PictureBox controls.
I'd like to determine which was used to activate the contextual menu.
I did the following in the Click event for a given menu item, which seems awkward:
MenuItem_Click(object sender, EventArgs e)
{
PictureBox Origin = (PictureBox)sender;
switch (Origin.Name)
{
case "pbOne":
// do something with #1
break;
case "pbTwo":
// do something with #2
break;
}
}
Working with the control name is the part that feels awkward.
Can you suggest a better way?
Edit:
Casting sender
to a PictureBox does not work, as I forgot the menu item would be the sender, not the PictureBox. So I will have to further backtrack.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用
SourceControl
< /a> 属性:Simply use
SourceControl
property:不太确定你是如何做到这一点的。 发送者是菜单项,而不是图片框。如果这确实有效,那么您已经拥有了要修改的图片框的引用。这是起源。不需要 switch 语句。
另一种可行的方法是使用 Opening 事件:
您现在可以在任何菜单项 Click 事件处理程序中使用 currentBox。它之所以有效,是因为同时只能打开一个菜单。
Not so sure how you made that work. The sender is the menu item, not the picture box. If this actually works then you already have the reference to the picture box you want to tinker with. It's Origin. No need for the switch statement.
Another way that works is to use the Opening event:
And you can now use currentBox in any of the menu item Click event handlers. It works because there can be only one menu open at the same time.