程序化按钮单击会抛出'System.StackOverflowException'异常

Cra*_*d22 9 c# stack-overflow click button simulate

我在C#.Net中编写了一个WinForms程序,在密码表单中以编程方式单击按钮.

Form1加载并显示Form2为对话框.

如果DialogResult是DialogResult.OK的其他任何东西,应用程序将关闭.

到目前为止,我有一个按钮单击事件,编码如下:

 if (txtpass.Text == "")
            {
                MessageBox.Show("You need to enter a password", "Password", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                txtpass.Focus();
            }
            else
            {
                if (txtpass.Text == "1234")
                {
                    radButton1.DialogResult = DialogResult.OK;
                    radButton1.PerformClick();
                }
                else
                {
                    MessageBox.Show("Password Incorrect", "Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtpass.Text = "";
                    txtpass.Focus();
                }
            }
Run Code Online (Sandbox Code Playgroud)

我用radButton1.PerformClick();,但运行程序给我以下消息:

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
Run Code Online (Sandbox Code Playgroud)

我不确定导致此异常的原因是什么.

jjn*_*guy 7

编辑不是猜测.告诉按钮从内部单击它本身肯定会导致无限循环.这会导致方法被反复调用,填满堆栈并导致堆栈溢出.

我的猜测是调用PerformClick()会导致您发布的当前方法再次被调用,从而导致无限的调用循环并导致a StackOverflowException.

为了防止这种情况,您需要在代码中的某处修复逻辑,以便:

if (txtpass.Text == "1234")
Run Code Online (Sandbox Code Playgroud)

求值为,false并且不会一遍又一遍地调用click方法.您可以通过txtpass.Text = ""在使其再次单击之前进行设置来实现此目的.