Search code examples
c#winformsselectfocusform-control

Trouble with setting focus/select to Form1 after I show Form2 using AxAcroPDFLib


As per title, I am having trouble selecting and setting focus to a control in Form1 right after I show Form2. Any idea why the below code is not working?

public partial class MainForm : Form
{
     public Form2 frm2;

     ...

     public void ReadThroughContents(int index)
     {
        ...

        if (frm2.IsDisposed || frm2 == null) { frm2 = new Form2(); }
        if (!frm2.Visible) { frm2.Show(); }

        this.listbox1.Focus();
        this.listbox1.Select();

        ...
     }

EDIT: Just to make it clear, the focus stays on Form2. I am however able to select and focus on Form1 manually by clicking on the form, but I need this to be done automatically.

EDIT: In Form2 I am using the AxAcroPDFLib library. A PDF file is loaded in Form2 when it is shown. I believe that this is what is preventing Form1 to get focus. I have tried without loading the PDF file and I can automate focus.

Cheers.


Solution

  • Found a solution thanks to @defaultlocale above!

    Code copied from here

    private void returnFocus(object sender, EventArgs e)
        {
            lstboxItems.Focus();
        }
    this.lstboxItems.LostFocus += new System.EventHandler(this.returnFocus);