简体   繁体   中英

Compact Framework 3.5 text field set focus not working

I use the code below to set focus to a text field:

public void setFieldInFocus(TabPage tabPage)
    {
        foreach (Control t in tabPage.Controls)
        {
            if (t is TextBox)
            {
                if (t.Name == fieldInFocus)
                {
                    t.Focus();              

                }
            }

        }

    }

The cursor is displayed in the text field however when i try to enter text using the mobile keypad nothing happens until I click on the text field, even though the cursor was already in the text field. Then I click on the text field and try to enter text using the mobile keypad and it works. Why do I have to still click the text field to enter text? What can I do to solve this problem?

please note that I am using compact framework 3.5 and textField.Select(); is not available.

Thanks

When is the code snippet you posted executing? Is it before the form is actually displayed? If so, the .NET runtime will override your manual focus setting and change it to the first focusable control on the form.

Even though the cursor appears inside the textbox, it may not be the control that has the focus.

One solution that I would consider less-than-ideal would be to drop a timer on your form with a very short interval (say 10) that is enabled when the form load event fires. In the timer_tick handler, disable the timer (ensuring it only runs one time) and then execute your code snippet. Executing the code in this manner ensures that the windows message pump has a chance to completely load and display your form (and in the process executing it's default focus routine) before your focus override code executes.

A better way to mitigate this issue is to try to design your form in such a way that your textbox is the first focusable item. By default, the form will iterate it's child control tree in a depth-first manner, and once it finds a control that is focusable, it focuses that one and kicks out.

If you take a look at the designer code file for your form, try manually adjusting it so you ensure that:

  1. the textbox is the first control added to the tab page
  2. the tabpage is the first control added to the tab control
  3. that the tabcontrol is the first control added to the form.

When these three things are true, the textbox will be focused first by default and you won't have to run any other code to override that.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM