Magic Mick
Magic Mick

Reputation: 1523

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.

Upvotes: 0

Views: 583

Answers (2)

Magic Mick
Magic Mick

Reputation: 1523

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

Upvotes: 0

default locale
default locale

Reputation: 13436

Just to make it clear, the focus stays on Form2.

This happens because Form.Show steals the focus.

You may try to bring focus back to Form1 before setting focus to specific controls. You can use Form.Activate to do this:

//...
this.Activate();
this.listbox1.Focus();
//...

Check out this quesiton if you want to always show Form2 without stealing focus: Show a Form without stealing focus?

Upvotes: 1

Related Questions