我正在用 C# 编写一个 WinForm 应用程序。有一个点击Form A
打开Form C
。Button
现在,我想Form B
在打开之前添加一个密码输入屏幕Form C
。只有输入的密码正确才会Form C
打开,否则显示错误消息。Form B
只有一个TextBox
控件和一个验证 Button
控件。
/*Form A*/
FormB fb;
private void BtnClick(object sender, EventArgs e) {
DialogResult result;
//fb can open once at a time
if(fb == null){
fb = new FormB();
fb.FormClosed += new FormClosedEventHandler(FormB_FormClosed);
//This seems to be not working
result = fb.ShowDialog();
}
else //FormB already open. Do nothing
return;
//Only if password entered is correct, proceed
if(result == DialogResult.Yes){ //result == cancel
//Code to open Form C //Program never reaches here
}
}
//Upon closing FormB, reset it to null
private void FormB_FormClosed(object sender, FormClosedEventArgs e){
if(fb != null)
fb = null;
}
/* Form B */
private const string password = "xxxyyyzzz";
private void BtnPW_Click(object sender, EventArgs e){
bool result = Verify();
if(result){
BtnPW.DialogResult = DialogResult.Yes;
}
else{
MessageBox.Show("Error: Incorrect password");
BtnPW.DialogResult = DialogResult.No;
}
this.Close(); //Added
}
private bool Verify(){
if(TxtBox.Text == password)
return true;
else
return false;
}
有人能告诉我这段代码有什么问题吗?if
它永远不会到达Form A
.
编辑:即使我输入正确的密码并点击按钮Form B
,也会result
得到Form A
“DialogResult.Cancel`。