To summarise what I think your requirements are:
1. The User should be able to close the form whether there is data in the TextBox or not. This is perfectly reasonable - you should not force the user to enter valid data when they are trying to leave the application.
2. If the User attempts to close the form then you want to prompt them to make sure they really do want to leave.
3. If invalid data is entered then you want the focus to stay in the textbox after you have displayed the error message.
So ...
Firstly, use the
Validating
event for the TextBox not the Leave event. It's the right place to put validation (the clue is in the name :)). This gives you much more power over controlling the close-down process (see below) and also means that you can just use
e.Cancel = true;
instead of attempting to refocus on the TextBox.
Next, make sure that hitting the Close button does not cause validation. In general this will mean that none of the Validating events will be called (for any control) - which is what you want when you just want to get out of there.
You also need to consider what will happen when the user just hits the (X) at the top of the form or uses the Alt-F4 shortcut. I've assumed that you want to prompt them in just the same way as if they had hit the Close button.
Here is a full solution:
private void Form1_Load(object sender, EventArgs e)
{
btnClose.CausesValidation = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
private bool QueryExit()
{
return (MessageBox.Show("Do you want to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) ==
DialogResult.Yes);
}
private void txtDealer_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (txtDealer.Text == "")
{
MessageBox.Show("Please Enter dealer");
e.Cancel = true;
}
}
protected override void WndProc(ref Message m)
{
const int WM_CLOSE = 0x0010;
if (m.Msg == WM_CLOSE)
AutoValidate = AutoValidate.Disable;
base.WndProc(ref m);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!QueryExit()) e.Cancel = true;
}
That WndProc method is overriding the Windows message handler to stop all validations when the user hits the (X) or Alt-F4 ... it's comparable to setting the
CausesValidation = false;
Notice that the btnClose_Click no longer asks the user if they want to exit - that is because it is always going to be called from the FormClosing event and we don't want to display the message twice