Not logged in - Login

Capture the 'X' close event to stop validation

The following code demonstrates how to stop the validation on a field from preventing a form from being closed when the 'X' button is pressed on the form.

//const for checking for the X close
public const int SC_CLOSE = 61536;
public const int WM_SYSCOMMAND = 274;
protected override void WndProc(ref Message m)
{
   if (m.Msg == WM_SYSCOMMAND && m.WParam.ToInt32() == SC_CLOSE)
   {
      // If we come in here, the user pressed the 'X' box on the form to close it.
      // Clear out anything in the item number field.
      // Leaving random text in here may cause the validation to fail, 
      // which would prevent the form from closing.
      this.txtMyField.Text = string.Empty;
   }

   base.WndProc(ref m);
}