R – How Do You “Lock” the focus of a form to a specific control

focusnetwinforms

How does one lock the focus of a .net application to a specific control? For example, if I have a form with 5 text boxes, and I want them filled out in a specific order, how can I stop someone who is in box 1 from tabbing/clicking to box 2, or hitting OK or Cancel or anything else? Is there an easy way, or do I have to manually disable/enable each other control at the appropriate time?

The trouble with the obvious solution (Reset Focus when Focus is Lost) is that MSDN says you can lock up your machine that way:

(Source:http://msdn.microsoft.com/en-us/library/system.windows.forms.control.leave.aspx)

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 in the "Keyboard Input Reference" section, and the "Message Deadlocks" section of the "About Messages and Message Queues" topic in the MSDN library at http://msdn.microsoft.com/library.

Best Answer

Handle the Leave event of your textBox1. Inside the event handler, if your conditions are not met, for e.g. if the user has not entered some input, reset the focus back to the control.

private void textBox1_Leave(object sender, EventArgs e)
{
    if string.isNullOrEmpty(textBox1.Text)
    {
        textBox1.focus();
    }
}

Do this for each of your controls or do it more generic like:

private void textBox_Leave(object sender, EventArgs e)
{
    TextBox textBox = sender as TextBox;
    if (string.isNullOrEmpty(textBox.Text)
    {
        textBox.focus();
    }
}