Control.OnClick(EventArgs) 方法

定义

引发 Click 事件。

C#
protected virtual void OnClick(EventArgs e);

参数

e
EventArgs

包含事件数据的 EventArgs

示例

下面的代码示例演示如何在派生类中重写 OnClick 方法。 若要运行该示例,请将以下代码粘贴到同一文件中的窗体类后面。 向窗体添加类型 SingleClickTextBox 为的文本框。

C#
// This is a custom TextBox control that overrides the OnClick method
// to allow one-click selection of the text in the text box.

public class SingleClickTextBox: TextBox

{
    protected override void OnClick(EventArgs e)
    {
        this.SelectAll();
        base.OnClick(e);
    }
}

下面的代码示例演示事件和事件处理程序的 Click 众多用法之一。

C#
// This example uses the Parent property and the Find method of Control to set
// properties on the parent control of a Button and its Form. The example assumes
// that a Button control named button1 is located within a GroupBox control. The 
// example also assumes that the Click event of the Button control is connected to
// the event handler method defined in the example.
private void button1_Click(object sender, System.EventArgs e)
{
   // Get the control the Button control is located in. In this case a GroupBox.
   Control control = button1.Parent;
   // Set the text and backcolor of the parent control.
   control.Text = "My Groupbox";
   control.BackColor = Color.Blue;
   // Get the form that the Button control is contained within.
   Form myForm = button1.FindForm();
   // Set the text and color of the form containing the Button.
   myForm.Text = "The Form of My Control";
   myForm.BackColor = Color.Red;
}

注解

引发事件时,将通过委托调用事件处理程序。 有关详细信息,请参阅 处理和引发事件

OnClick 方法还允许派生类对事件进行处理而不必附加委托。 这是在派生类中处理事件的首选技术。

继承者说明

在派生类中重写 OnClick(EventArgs) 时,一定要调用基类的 OnClick(EventArgs) 方法,以便已注册的委托对事件进行接收。

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另请参阅