c# - 如何判断点击事件在哪里触发

标签 c# click

在 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 正确获取了 ToolStripItemContextMenuStrip 的类名 - 我有点生疏,不知道这些心不再 – 更新了我的帖子,感谢@Mesko。

但在最后一步,您取回了打开上下文菜单的控件,并且单击了菜单项。这是一个“通用”控件,但您始终可以获取该控件的 .Name,然后根据名称将各个 PictureBox 分开。

关于c# - 如何判断点击事件在哪里触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20734029/

相关文章:

c# - 如何指定通用源文件和属性并让它们出现在 Visual Studio 中

c# - .NET Core 的可选构造函数注入(inject)参数

PHP循环遍历JSON多维数组并在单击按钮时加载数据

iPhone:如何为自定义键盘制作按键声音?

java - Android 工具栏菜单项点击

单击时清除 jQuery 表单字段

javascript - 无法在 gridview 内单击按钮时触发 jQuery 函数

c# - 如何将所有记录合并为 2 条记录并删除所有未合并的记录?

c# - 如何为一组具有几乎相同功能但具有不同参数和返回类型的类创建接口(interface)?

c# - 如何在 C# 中获取精确的日期时间