You want to find the focused TextBox in your Windows Forms program. There are many commands that require to know what the focused TextBox is, and whether any TextBox is focused. These include text insertion, copy and paste, cut and undo, and find in this page.
First, I want to note that every TextBox or control has a Focused property. This is set to true and false depending on the state of the TextBox. In the first example, I show a method that loops through all the controls on a form and returns the TextBox that has focus.
private TextBox TextFocusedFirstLoop()
{
// Look through all the controls on this form.
foreach (Control con in this.Controls)
{
// Every control has a Focused property.
if (con.Focused == true)
{
// Try to cast the control to a TextBox.
TextBox textBox = con as TextBox;
if (textBox != null)
{
return textBox; // We have a TextBox that has focus.
}
}
}
return null; // No suitable TextBox was found.
}
private void SolutionExampleLoop()
{
TextBox textBox = TextFocusedFirstLoop();
if (textBox != null)
{
// We have the focused TextBox. We can modify or
// check parts of it.
}
}The code I showed above works well and is reliable, and in rapid application development, it may even be better. But here I want to present a method that is customized for each program and works faster overall. It is also simpler to understand and shorter. However, it must be maintained more carefully.
private TextBox TextFocusedFirst()
{
// mainBox2 is a TextBox control.
if (mainBox2.Focused == true)
{
return mainBox2;
}
// titleBox2 is a TextBox control.
if (titleBox2.Focused == true)
{
return titleBox2;
}
// passwordTextBox is a TextBox control.
if (passwordTextBox.Focused == true)
{
return passwordTextBox;
}
return null; // Nothing is focused, so return null.
}
private void SolutionExample()
{
TextBox textBox = TextFocusedFirst();
if (textBox != null)
{
// We have the focused TextBox. We can modify or
// check parts of it.
}
}The second method is shorter and simpler, and benchmarks are shown next. This approach wins my recommendation. The performance difference is not really dramatic but it may be larger on more complex programs.
| 1 - Loop method | 2 - Manual check method | |
| Times in ms | 10218 18431 35621 | 7653 15358 22653 |
| Average time in ms | 21423 | 15221 |
It is clear that the method that the second method I show in this document is the faster one. There is a tradeoff, however, and in a few situations it might make sense to choose the loop method instead. Here the method approach itself is more important than the benchmark, and I feel the second example provides a good example of finding the focused control to use in your C# .NET programs.