Sunday, December 28, 2008

Windows Forms SetFocus to any control

Recently came across a developer need to have a utility that sets focus to a control anywhere on a windows form. Well, you might know about the Focus method of the controls but that might not navigate to the control in cases, say for example, when you have tab pages. So wrote this quick utility that takes the name of the control and a base control where to start the drill down (for most instances, you might want to give the base form here).

The code builds the list of controls recursively by finding the control and it's parents in parent-child hierarchy. Let's look at a simple code snippet for it:


namespace MyProject.ClientUtility
{
/// <summary>
/// Utility class for forms controls
/// </summary>
public class FormsUtility
{
private List<Control> _focusControlsList = new List<Control>();

public FormsUtility() { }

#region Set Focus to Control
/// <summary>
/// Set focus to a control based on the control name.
/// Pass base(parent) control to loop through all child controls.
/// </summary>
/// <param name="controlName"></param>
/// <param name="baseControl"></param>
/// <returns></returns>
public void SetFocusTo(string controlName, Control baseControl)
{
// Build the control list from parent to child order
BuildControlList(controlName, baseControl);
// Set focus in that order:
foreach (Control eachControl in _focusControlsList)
SetFocus(eachControl);
}

/// <summary>
/// Build the control list from Top-Down
/// </summary>
/// <param name="controlName"></param>
/// <param name="baseControl"></param>
/// <returns></returns>
private bool BuildControlList(string controlName, Control baseControl)
{
if (baseControl.Name == controlName)
{
_focusControlsList.Insert(0, baseControl);
return true;
}
foreach (Control eachControl in baseControl.Controls)
{
if (eachControl.Name == controlName)
{
_focusControlsList.Insert(0, eachControl);
return true;
}
if (eachControl.HasChildren)
{
// recursive...
if (BuildControlList(controlName, eachControl))
{
// going back to each parent to set focus
_focusControlsList.Insert(0, eachControl);
return true;
}
}
}
return false;
}

/// <summary>
/// Focus based on type of control
/// </summary>
/// <param name="controlToFocus"></param>
private void SetFocus(Control controlToFocus)
{
switch (controlToFocus.GetType().ToString())
{
case "System.Windows.Forms.TabPage":
// TabPage must be selected
((TabControl)((TabPage)controlToFocus).Parent).SelectedTab =
(TabPage)controlToFocus;
break;
default:
controlToFocus.Focus();
break;
}
}
#endregion
}
}

Love coding!

No comments: