A control’s Validating event is hit even when the user clicks on the Close box. How can I avoid this behavior

Platform: WinForms| Category: Controls

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.

	private bool tabKeyPressed = false;

	private void textBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
	{
		if(tabKeyPressed ||
      			this.ClientRectangle.Contains(this.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);
	}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.