简体   繁体   English

C#点击控件

[英]C# click on control

I'm trying to create a custom control which fires an even on click. 我正在尝试创建一个自定义控件,可以在点击时触发。 My control is just a panel with a couple of labels and a picturebox inside. 我的控件只是一个面板,里面有几个标签和一个图片框。

The click works perfectly, the only issue is that I have to click the background of the control and if I press on the picturebox, is not working. 点击工作完美,唯一的问题是我必须单击控件的背景,如果我按下图片框,则无法正常工作。

I've added the on click event to the control, but I would like to press in every place of it to trigger the event, not just the background of the panel. 我已将on click事件添加到控件中,但我想在其中的每个位置按下以触发事件,而不仅仅是面板的背景。

I thought about adding a transparent object that covers entirely the control. 我想添加一个完全覆盖控件的透明对象。 I actually don't like this idea, however, I've tried with a picturebox, but i cannot see through it. 我实际上不喜欢这个想法,但是,我尝试过一个图片盒,但我无法看透它。 It's not transparent. 它不透明。 I can just see the panel background but It covers the labels and the image. 我只能看到面板背景,但它涵盖了标签和图像。

Thanks for the support. 感谢您的支持。

If you just have a couple of objects in your panel, you can hook the Click event of all objects it contains to the same event handler, there is nothing wrong doing this. 如果你的面板中只有几个对象,你可以将它包含的所有对象的Click事件挂钩到同一个事件处理程序,这样做没有错。

public class MyUserControl : UserControl
{
    public event Action<MyUserControl> MyControlClick

    public string ID {get; set;}

    public MyUserControl()
    {
        InitializeComponents();

        // The same event handler code will be used for the three controls
        myPictureBox.Click += global_Click;
        myLabel1.Click += global_Click;
        myLabel2.Click += global_Click;
        this.Click += global_Click;
    }

    void global_Click(object sender, EventArgs e)
    {
        if (MyControlClick != null)
            MyControlClick(this);
    }
}

If you have a more important amount of objects, you can rely on this answer to create a truly transparent panel that handles clicks. 如果您拥有更重要的对象数量,则可以依靠此答案创建一个真正透明的面板来处理点击。 The drawback is that you will have to detect which object has been clicked by using HitTest based on the mouse location. 缺点是您必须根据鼠标位置使用HitTest单击了哪个对象。

On the form side : 在表格方面:

aControl.MyControlClick += aControl_MyControlClick;

// ...

// This code is triggered when a MyUserControl is clicked
void aControl_MyControlClick(MyUserControl ctl)
{
    MessageBox.Show(ctl.ID);
}

Actually! 其实! You cannot raise any event to the element in the Usercontrol unless you have to apply own method to your usercontrol or you can disable the element in the usercontrol but it will change the color of that element but It will raise the click event when you click your control. 您不能向Usercontrol中的元素引发任何事件,除非您必须将自己的方法应用于您的usercontrol,或者您可以在usercontrol中禁用该元素,但它将更改该元素的颜色但它会在您单击时引发单击事件控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM