简体   繁体   中英

C# Custom click event that not inherit from Control

Can i implement a custom click event that raise when user click on my object.

My object doesn't inherit any class but it has a Location Width Height properties.

Question is : i don't know how code that when i create MyObj subscribe to click event.

public delegate void CusEventHandler(object sender, CusEventArgs e);
public class MyObject
{
    private Point location;
    private int width;
    private int height;
    public event CusEventHandler Click;
    public MyObject(Point loc, int w, int h)
    {
        this.location = loc;
        this.width= w;
        this.height= h;
    }
    protected virtual void OnClick(CusEventArgs e)
    {
        if (Click != null)
        {
            Click(this, e);
        }
    }
}
public partial class Form1 : Form
{
    public MyObject myObj;
    public Form1()
    {
        InitializeComponent();
        myObj = new (new Point(5,5),100,100);
        myObj.Click+= new CusEventHandler(myObj_click);
    }
    private void myObj_click(object sender,CusEventArgs e)
    {
        //Some logic
    }
}

You are recommenced inheriting your class from Control, so that hit testing is already done for you. See also this post.

If you can't replicate the logic used in clickable controls like System.Windows.Controls.Button then you can't do that. You must inherit from a control which provides a Click -event. This is why there is inheritance and most of the controls offer you to inherit from them.

Additonally, if your control did inherit from a base class like System.Windows.Controls.Control you can't use it in Windows either.

See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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