将控件的 MouseClick 事件传递给它的容器 [英] Passing control's MouseClick event to its container

查看:20
本文介绍了将控件的 MouseClick 事件传递给它的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会尽量简洁但易于理解.我有一个 PictureBox 元素的动态二维数组,它们都通过以下方式添加到同一个表单中:

I'll try to be concise but comrehensible. I have a dynamic 2-dimensional array of PictureBox elements, and they're all added to the same form via:

this.Controls.Add(PictureBoxArray[i,j]);

现在我已经设计了一个算法来确定哪些 PB 被点击,但我已经将它放在 ParentForm_MouseClick 方法中.现在我遇到了一个悖论.我创建的算法返回正确的输出,但仅当我单击表单中的空白区域时才会调用 ParentForm_MouseClick 方法,而不是当我单击图片框时.所以我的问题是 - 当用户单击表单中的任意位置时,我如何调用 ParentForm_MouseClick 方法,即我可以以某种方式覆盖 PictureBoxes 的 MouseClick 事件,以便调用 ParentForm_MouseClick 吗?

Now I've designed an algorithm that would determine which of these PBs are clicked, but I've placed it in the ParentForm_MouseClick method. And now I've reached a paradox. The algorithm I've created returns the proper output, but the ParentForm_MouseClick method is called only when I click on the empty space in the Form, not when I click on PictureBoxes. So my question is - how can I invoke ParentForm_MouseClick method when users click anywhere in the form i.e. can I somehow override PictureBoxes' MouseClick events so that ParentForm_MouseClick is invoked instead?

这刚刚发生在我身上,我可以创建一个自定义的 PictureBoxClass 类来扩展 .NET 类,并只覆盖 MouseClick() 事件来调用我之前编写的方法吗?

This just occured to me, could I create a custom PictureBoxClass Class that extends the .NET one and just override the MouseClick() event to invoke a method I've previously written?

推荐答案

看起来你把事情复杂化了.如果您需要从不同位置调用事件处理程序中的代码,最好将其抽象为不同的方法.您可以将相同的事件处理程序附加到 PictureBoxes,然后调用该方法.

It seems like you're over-complicating things. If you're going to need to call the code within an event handler from different places, it's a good idea to abstract that out to a different method. You can attach the same event handler to the PictureBoxes which then call that method.

for(int i = 0; i < PictureBoxArray.GetLength(0); i++) 
{
    for(int j = 0; j < PictureBoxArray.GetLength(1); j++)
    {
        //attach handler
        PictureBoxArray[i,j].Click += pictureBox_Click;
    }
}


void pictureBox_Click(object sender, EventArgs e)
{
   MyMethod();      
}

void parentForm_Click(object sender, EventArgs e)
{
   MyMethod();       
}

private void MyMethod()
{
   //method to be called
}

这篇关于将控件的 MouseClick 事件传递给它的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆