我在 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();
}
}
我使用 radButton1.PerformClick();
,但运行该程序时出现以下消息:
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
我不确定是什么导致抛出此异常。
最佳答案
编辑 不是猜测。告诉按钮从自身内部单击本身肯定会导致无限循环。这会导致该方法被反复调用,填满堆栈并导致其溢出。
我的猜测是调用 PerformClick()
会导致您发布的当前方法再次被调用,从而导致无限调用循环并导致 StackOverflowException
。
为防止这种情况,您需要在代码中的某处修复逻辑,以便:
if (txtpass.Text == "1234")
评估为 false
并且不会一遍又一遍地调用 click 方法。您可以通过在使其再次点击自身之前设置 txtpass.Text = ""
来实现这一点。
关于c# - 程序化按钮单击引发 'System.StackOverflowException' 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2271883/