C# winform 清除鼠标事件参数

C# winform Clear mouse event arg

//是否可以为2个文本框创建1个鼠标?

假设我有 2 个文本框,(TxtBox1, TxtBox2)

我想要的是 1 个清除函数,它只清除被点击的文本按钮,而不需要为每个按钮创建 2 个清除函数:TxtBox1.Clear(); TxtBox1.Clear();

这是我认为 C# 支持的另一种解释:

    private void Clear(object sender, MouseEventArgs e)
    {
        this.Clear();
              }

sender 是被单击的 UI 元素,因此以下应该有效:

private void TextBoxOnClick(object sender, MouseEventArgs e)
{
    var theTextBox = sender as TextBox;
    if (theTextBox != null)
    {
        theTextBox.Text = string.Empty;
    }
}

as 和检查 null 只是防御性编程。如果您确定这只会从 TextBox 调用,那么您可以进行直接转换。

然后您需要将此添加到每个文本框的点击事件处理程序中:

TxtBox1.OnClick += TextBoxOnClick;
TxtBox2.OnClick += TextBoxOnClick;

等用于所有文本框。