Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I prevent a control from processing the Validating event when the user clicks on the Close box?

One way is to add code to your Validating handler and only execute the validation routine if the mouse is in the client area. This will avoid the click on the title bar and its system menu. You might also want to add special handling for the tab key so your validation is hit independent of the mouse location when you tab off the control.

using System.ComponentModel;

private bool tabKeyPressed = false; 

private void textBox1_Validating( object sender, CancelEventArgs e ) 
{ 
  if ( tabKeyPressed || ClientRectangle.Contains( PointToClient( Cursor.Position ) ) ) 
    if ( boolNotOKValues ) // do your validating 
      e.Cancel = true; // failed 

  tabKeyPressed = false; 
}

protected override bool ProcessDialogKey( Keys keyData ) 
{ 
  tabKeyPressed = keyData == Keys.Tab; 
  return base.ProcessDialogKey( keyData ); 
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter