创建我自己的控件

Create My Own Control

我想创建自己的文本框控件,当我在其上单击鼠标右键时出现事件。我该怎么做?

这很简单,困难的部分在于如何引发事件:

public class MyMagicTextbox : TextBox
{
    public event EventHandler<EventArgs> MyMagicEvent;

    protected virtual void OnMyMagicEvent(EventArgs e)
    {
        MyMagicEvent?.Invoke(this, e);
    }
}

继承一个文本框(或其他控件)并赋予它新的 methods/events 真的就是这么简单。您必须决定引发该事件的逻辑以及消费应用程序如何使用它。


根据评论编辑:

for example I want to make a textbox and define an event which arise when mouse's right button will be clicked on it..

然后您必须为鼠标单击消耗(使用 OnXXX 事件名称),然后引发您的自定义事件:

public class MyMagicTextbox : TextBox
{
    public event EventHandler<EventArgs> MyMagicEvent;

    protected virtual void OnMyMagicEvent(EventArgs e)
    {
        MyMagicEvent?.Invoke(this, e);
    }

    protected override void OnMouseClick(MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
            OnMyMagicEvent(EventArgs.Empty);

        base.OnMouseClick(e);
    }
}