0

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.

Magic Mick
  • 1,475
  • 1
  • 21
  • 32

2 Answers2

1

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?

Community
  • 1
  • 1
default locale
  • 13,035
  • 13
  • 56
  • 62
  • This would work without me using AxAcroPDFLib... I believe that my problem is much more complicated. Thanks for the help tho. – Magic Mick Jul 31 '14 at 05:59
  • 1
    @TonyMontana I have no experience with Acrobat SDK. Search bring me to this [question](http://stackoverflow.com/questions/8996191/display-pdf-takes-focus-and-eats-hot-key), take a look on Hans Passant's comment there – default locale Jul 31 '14 at 06:06
0

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);
Community
  • 1
  • 1
Magic Mick
  • 1,475
  • 1
  • 21
  • 32