Home > Net >  Form.invoke not focusing on control
Form.invoke not focusing on control

Time:08-27

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();
        }
    }

CodePudding user response:

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

  • Related