Control.LostFocus Event

Definition

Occurs when the control loses focus.

public:
 event EventHandler ^ LostFocus;
[System.ComponentModel.Browsable(false)]
public event EventHandler LostFocus;
[System.ComponentModel.Browsable(false)]
public event EventHandler? LostFocus;
[<System.ComponentModel.Browsable(false)>]
member this.LostFocus : EventHandler 
Public Custom Event LostFocus As EventHandler 

Event Type

Attributes

Examples

The following code example demonstrates validating the text for TextBox1. It also demonstrates handling the LostFocus event by setting the FileDialog.InitialDirectory property to the text in TextBox1. The code example used the ErrorProvider.GetError method to check for an error before opening the file dialog box. To run this example, paste the following code into a form containing a TextBox named TextBox1, an OpenFileDialog named OpenFileDialog1, a Button named Button1, and an ErrorProvider named ErrorProvider1. Ensure all events are associated with their event handlers.

private:
   void TextBox1_Validating( Object^ sender,
      System::ComponentModel::CancelEventArgs^ e )
   {
      // If nothing is entered,
      // an ArgumentException is caught; if an invalid directory is entered, 
      // a DirectoryNotFoundException is caught. An appropriate error message 
      // is displayed in either case.
      try
      {
         System::IO::DirectoryInfo^ directory = gcnew System::IO::DirectoryInfo( TextBox1->Text );
         directory->GetFiles();
         ErrorProvider1->SetError( TextBox1, "" );
      }
      catch ( System::ArgumentException^ ) 
      {
         ErrorProvider1->SetError( TextBox1, "Please enter a directory" );
      }
      catch ( System::IO::DirectoryNotFoundException^ ) 
      {
         ErrorProvider1->SetError( TextBox1, "The directory does not exist."
         "Try again with a different directory." );
      }
   }

   // This method handles the LostFocus event for TextBox1 by setting the 
   // dialog's InitialDirectory property to the text in TextBox1.
   void TextBox1_LostFocus( Object^ sender, System::EventArgs^ e )
   {
      OpenFileDialog1->InitialDirectory = TextBox1->Text;
   }

   // This method demonstrates using the ErrorProvider.GetError method 
   // to check for an error before opening the dialog box.
   void Button1_Click( System::Object^ sender, System::EventArgs^ e )
   {
      //If there is no error, then open the dialog box.
      if ( ErrorProvider1->GetError( TextBox1 )->Equals( "" ) )
      {
         ::DialogResult dialogResult = OpenFileDialog1->ShowDialog();
      }
   }
private void textBox1_Validating(object sender, 
    System.ComponentModel.CancelEventArgs e)
{
    // If nothing is entered,
    // an ArgumentException is caught; if an invalid directory is entered, 
    // a DirectoryNotFoundException is caught. An appropriate error message 
    // is displayed in either case.
    try
    {
        System.IO.DirectoryInfo directory = 
            new System.IO.DirectoryInfo(textBox1.Text);
        directory.GetFiles();
        errorProvider1.SetError(textBox1, "");
    }
    catch(System.ArgumentException ex1)
    {
        errorProvider1.SetError(textBox1, "Please enter a directory");
    }
    catch(System.IO.DirectoryNotFoundException ex2)
    {
        errorProvider1.SetError(textBox1, "The directory does not exist." +
            "Try again with a different directory.");
    }
}

// This method handles the LostFocus event for textBox1 by setting the 
// dialog's InitialDirectory property to the text in textBox1.
private void textBox1_LostFocus(object sender, System.EventArgs e)
{
    openFileDialog1.InitialDirectory = textBox1.Text;
}

// This method demonstrates using the ErrorProvider.GetError method 
// to check for an error before opening the dialog box.
private void button1_Click(System.Object sender, System.EventArgs e)
{
    //If there is no error, then open the dialog box.
    if (errorProvider1.GetError(textBox1)=="")
    {
        DialogResult dialogResult = openFileDialog1.ShowDialog();
    }
}
Private Sub TextBox1_Validating(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles TextBox1.Validating

    ' If nothing is entered,
    ' an ArgumentException is caught; if an invalid directory is entered, 
    ' a DirectoryNotFoundException is caught. An appropriate error message 
    ' is displayed in either case.
    Try
        Dim directory As New System.IO.DirectoryInfo(TextBox1.Text)
        directory.GetFiles()
        ErrorProvider1.SetError(TextBox1, "")

    Catch ex1 As System.ArgumentException
        ErrorProvider1.SetError(TextBox1, "Please enter a directory")

    Catch ex2 As System.IO.DirectoryNotFoundException
        ErrorProvider1.SetError(TextBox1, _
        "The directory does not exist." & _
        "Try again with a different directory.")
    End Try

End Sub

' This method handles the LostFocus event for TextBox1 by setting the 
' dialog's InitialDirectory property to the text in TextBox1.
Private Sub TextBox1_LostFocus(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles TextBox1.LostFocus
    OpenFileDialog1.InitialDirectory = TextBox1.Text
End Sub


' This method demonstrates using the ErrorProvider.GetError method 
' to check for an error before opening the dialog box.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

    'If there is no error, then open the dialog box.
    If ErrorProvider1.GetError(TextBox1) = "" Then
        Dim dialogResult As DialogResult = OpenFileDialog1.ShowDialog()
    End If

End Sub

Remarks

When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order:

  1. Enter

  2. GotFocus

  3. Leave

  4. Validating

  5. Validated

  6. LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

  1. Enter

  2. GotFocus

  3. LostFocus

  4. Leave

  5. Validating

  6. Validated

If the CausesValidation property is set to false, the Validating and Validated events are suppressed.

If the Cancel property of the CancelEventArgs is set to true in the Validating event delegate, all events that would usually occur after the Validating event are suppressed.

Note

The GotFocus and LostFocus events are low-level focus events that are tied to the WM_KILLFOCUS and WM_SETFOCUS Windows messages. Typically, the GotFocus and LostFocus events are only used when updating UICues or when writing custom controls. Instead the Enter and Leave events should be used for all controls except the Form class, which uses the Activated and Deactivate events. For more information about the GotFocus and LostFocus events, see the WM_KILLFOCUS and WM_KILLFOCUS topics.

Caution

Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Doing so can cause your application or the operating system to stop responding. For more information, see the WM_KILLFOCUS topic.

For more information about handling events, see Handling and Raising Events.

Applies to

See also