持续检查用户控件中的按钮是否被点击

Continuously check if button from usercontrol clicked

我有一个名为 class 的用户控件 PinPad。它包含一个 Button,我处理了它的点击事件 btnGetAccess_Click(object sender, EventArgs e) 和一个 属性,用于读取在 TextBox 中输入的 Password

我在我的 Form1 上放置了一个 PinPad 控件实例,它应该在单击按钮且密码正确时打开 Form2

因为我把它放在构造函数中,所以目前检查密码什么都不做,因为它只会在 Form1 加载并且尚未输入密码时检查密码。

那么如何让Form1在用户控件class中的按钮被点击后连续检查密码?

这是我当前的代码:

public Form1()
{
    InitializeComponent();
    if (pinPad1.Password == "123456")
    {
        // open form2
    }
}

使用Timer。有一个很好的例子。实现它,并且在密码输入正确并检查后不要忘记停止计时器。

你不需要检查一个按钮的连续点击。创建事件以订阅它们。然后他们会在事件发生时通知您。

您应该在您的用户控件中创建一个新事件并引发它,例如当您的用户控件中的按钮被点击时。然后您可以在表单中订阅该事件,并在那里 运行 您的逻辑。

示例:

[System.ComponentModel.DefaultEvent("ButtonClicked")]
public partial class SampleControl: UserControl
{
    public SampleControl()
    {
        InitializeComponent();
        button1.Click += button1_Click;
    }

    public event EventHandler ButtonClicked;
    protected virtual void OnButtonClicked(EventArgs e)
    {
        var handler = ButtonClicked;
        if (handler != null)
            handler(this, e);
    }
    private void button1_Click(object sender, EventArgs e)
    {
        //Do Stuff then raise event
        OnButtonClicked(EventArgs.Empty);
    }
}

您可以将控件放在窗体上并处理它的 ButtonClicked 事件。由于我们将 ButtonClicked 设置为控件的默认事件,当您在设计器中双击它时,它会创建事件处理程序并订阅事件:

private void sampleControl1_ButtonClicked(object sender, EventArgs e)
{
    MessageBox.Show("Button Clicked");
}

作为 C# 开发人员,您应该尽可能多地了解事件 类、方法、属性等。您可以了解更多 Handling and Raising Events