Very simple Windows Forms focus question :)

Posts   
 
    
Posts: 497
Joined: 08-Apr-2004
# Posted on: 29-Jul-2005 16:36:23   

Hi all,

I am trying to create a dead simple windows forms app - something I hardly ever do. All I need it to do is popup with a file dialog when it starts, and after the use chooses a file, then open the main form. I do this in the form constructor.....It all works, but when it runs, after you choose the file from the dialog, the focus for the main form is lost rage

I tried Form.ActiveForm.Focus(), but in the constructor that property returns null..... Do any of you windows forms experts have the answer?

Heres my code:

public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();



            if (fileName.Length < 1)
            {
                OpenFileDialog openDialog = Form1.GetFileName();
                DialogResult result = openDialog.ShowDialog(null);

                if(result != DialogResult.OK)
                {
                    return;
                }
                fileName = openDialog.FileName;
            }

            

        }
JimFoye avatar
JimFoye
User
Posts: 656
Joined: 22-Jun-2004
# Posted on: 29-Jul-2005 17:42:56   

I wouldn't be doing this in the constructor, which is really just for initializing an object. Do you agree? Maybe better to handle this in the Load event, for example.

Perhaps changing the code like that will make the problem solve itself.

jeffreygg
User
Posts: 805
Joined: 26-Oct-2003
# Posted on: 29-Jul-2005 18:26:36   

I agree with Jim here. The form technically hasn't been instantiated until the constructor has completed. Use Form.Load at which point the form has been instantiated and should automatically receive the focus once the dialog returns.

Jeff...