0

I asked a different version of this question before. Now i have another problem:

  1. I have a thread, working on "FormA"
  2. This thread working and firing an event,
  3. On that event, i show a new form "FormB" by using "FormA.Invoke".
  4. I have an event handler on "FormB". Its "FormB_Shown", in that method i focus on some textbox on "FormB" by using "Txt.Focus();"
  5. My problem is, when i call "FormA.InvokeIfRequired(() => { FormB.ShowDialog(); })", its not focusing on "Txt" on "FormB". Can someone please help?

I solved it by clicking on "Txt" location but its not a formal solution. What i miss here? My code like below;

Thread on "FormA" fired below event;

    private void OnMessage()
    {
        this.InvokeIfRequired(() =>
        {
            var loginForm = new LoginForm();
            loginForm.ShowDialog();
        });
    }

"FormB" has below method

    private void LoginForm_Shown(object sender, EventArgs e)
    {
        TxtUsername.Focus();
    }

"InvokeIfRequired" extension method like below;

    public static void InvokeIfRequired(this Control control, MethodInvoker action)
    {
        if (control.InvokeRequired)
        {
            control.Invoke(action);
        }
        else
        {
            action();
        }
    }
candogg
  • 145
  • 7
  • I tried SynchronizationContext cannot make it work. I change UI but focus not working. – candogg Aug 22 '22 at 11:39
  • Does this answer your question? [How do I put focus on a TextBox when a form loads?](https://stackoverflow.com/questions/6597196/how-do-i-put-focus-on-a-textbox-when-a-form-loads) – Sund'er Aug 22 '22 at 11:44
  • No. I tried it. I paste my code here; loginForm.Shown += (ss, ee) => { loginForm.ActiveControl = loginForm.TxtUsername; }; loginForm.ShowDialog(); – candogg Aug 22 '22 at 12:00
  • Like i said, i show form from external thread. I make call on UI thread by invoke. I think my problem is different then your suggestion. – candogg Aug 22 '22 at 12:02
  • Tab index is 0, activecontrol not working. Focus stays on window that on background. For example, I open a notepad in the background. When my thread triggers and opens my another form (TOPMOST FormB), I type text from keyboard. It all goes to notepad screen in the background. What should i do? FormB.Activate not working. – candogg Aug 22 '22 at 12:12
  • @candogg, if your app is in the background, opening a new form, even topmost, will *not* get the focus back on your app. Windows starting 7 does not allow apps to bring themselves to focus if they are in the background. – Nick Aug 22 '22 at 14:41
  • How can i set it to foreground? Yes thats the problem. Window starts deactivated. – candogg Aug 22 '22 at 19:09

1 Answers1

0

I found a solution by adding Thread.Sleep on form_shown event. After sleep, i activate form and set Form.ActiveControl property. Its done.

candogg
  • 145
  • 7