C# 检测用户何时尝试使用“确定”或“取消”关闭表单?
这听起来似乎应该有一个简单的解决方案,但我无法解决它 我有一个c#表单和一个C# 检测用户何时尝试使用“确定”或“取消”关闭表单?,c#,C#,这听起来似乎应该有一个简单的解决方案,但我无法解决它 我有一个c#表单和一个FormClosing事件处理程序: private void DrawBorderForm_FormClosing(object sender, FormClosingEventArgs e) { _dCornerRadius = 0.0; bool bIsDouble = false; try { bIsDouble = Double.TryParse(textBox
FormClosing
事件处理程序:
private void DrawBorderForm_FormClosing(object sender, FormClosingEventArgs e)
{
_dCornerRadius = 0.0;
bool bIsDouble = false;
try
{
bIsDouble = Double.TryParse(textBoxRadius.Text, out _dCornerRadius);
}
catch
{
bIsDouble = false;
}
if (!bIsDouble || _dCornerRadius < 0.0 || _dCornerRadius > 100.0)
{
MessageBox.Show("Please input a radius value of 0 to 100!");
e.Cancel = true;
return;
}
}
private void DrawBorderForm\u FormClosing(对象发送方,FormClosingEventArgs e)
{
_dCornerRadius=0.0;
bool-bIsDouble=假;
尝试
{
bisdool=Double.TryParse(textBoxRadius.Text,out\u dCornerRadius);
}
抓住
{
双倍=假;
}
如果(!bIsDouble | | | | | | | | | | | | | | | | | | | | | 124
{
Show(“请输入0到100的半径值!”);
e、 取消=真;
返回;
}
}
它验证一些文本值,如果值不是OK,则禁止关闭表单
问题是此处理程序同时为OK和Cancel和Close触发。我不需要验证他们是否取消或关闭。如果他们单击“确定”并因此想要关闭表单。您可以分析此对话框。DialogResult,在触发表单关闭事件时已设置此对话框。我找到了回答此问题的问题:
private void btnOK_单击(对象发送者,事件参数e)
{
_dCornerRadius=0.0;
bool-bIsDouble=假;
bisdool=Double.TryParse(textBoxRadius.Text,out\u dCornerRadius);
如果(!bIsDouble | | | | | | | | | | | | | | | | | | | | | 124
{
Show(“请输入0到100的半径值!”);
this.DialogResult=DialogResult.None;
}
}
从用户体验的角度来看,只要数据无效,“确定”按钮就不应被单击。但是出于您的特殊目的,您应该处理OK按钮的clicked事件,而不是表单关闭事件。然后只需在OK
中使用一个标志,这将有助于查看关闭此表单的代码。在实际关闭表单之前,当用户按下取消按钮时,应该设置一个变量,我们称之为“取消”。然后在FormClosing中检查该变量,如果该变量设置为true,则放弃所有数据。是否使用ShowDialog显示表单?如果是这样,您可以检查ShowDialog方法的结果。@GuillaumeCR我在使用OK处理程序的地方添加了一个答案。谢谢,谢谢。不过,我已经根据评论对其进行了调整,以使用“确定单击”处理程序。我将接受您的回答,因为它更直接地解决了问题。但我已经采纳了我自己的答案作为前进的方向。
private void btnOK_Click(object sender, EventArgs e)
{
_dCornerRadius = 0.0;
bool bIsDouble = false;
bIsDouble = Double.TryParse(textBoxRadius.Text, out _dCornerRadius);
if (!bIsDouble || _dCornerRadius < 0.0 || _dCornerRadius > 100.0)
{
MessageBox.Show("Please input a radius value of 0 to 100!");
this.DialogResult = DialogResult.None;
}
}