private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}
通过设置 e.Cancel = true,可以防止窗体关闭。
然而,在 内显示验证错误(通过某种方式突出显示违规字段,显示工具提示等) < strong > 并防止用户首先选择 OK 按钮,这将是一种更好的设计/用户体验。