John NoCookies
John NoCookies

Reputation: 1061

Display a form from the main form on startup

I want to display a small form when the program is ran. This is the code:

private void Form1_Load(object sender, EventArgs e)
{
    this.Opacity = 0;
    InitForm init = new InitForm();
    init.Show();
    init.BringToFront();
    comm = init.Start();
    this.Opacity = 100;
}

The Start() method draws some lines to the list box on the InitForm.

I have two problems:

  1. When the program starts, the list box is not populated, I just get the waiting cursor, then the main form is displayed and the box is populated at the same time;
  2. The InitForm is behind the main form. How do I bring it to front?

Upvotes: 0

Views: 521

Answers (4)

Kishore Kumar
Kishore Kumar

Reputation: 12874

You can bring the Init form to front by setting this property

init.TopMost=true 

It worked for me, check out,

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941515

Can't see a ListBox in that code. But painting doesn't happen until the UI thread goes idle again, after your Load event handler completes. Which also means that the Opacity assignment doesn't accomplish anything.

The Z-order problem is (partly) caused by this too, the main form isn't visible yet so BringToFront() doesn't work. Use either Show(this) so that InitForm is an owned window that always displays in front on the main form (recommended) or use the Shown event instead.

Upvotes: 1

Romias
Romias

Reputation: 14133

You should load the secondary form on a paralell thread. So, on the Form1's load event handler you trigger the second thread, showing the Form2.

Upvotes: 0

Haris Hasan
Haris Hasan

Reputation: 30097

When the program starts, the list box is not populated, I just get the
 waiting cursor, then the main form is displayed and the box is populated
 at the same time;

What do you expect should happen? Your UI Thread is busy in executing the code below

this.Opacity = 0;
InitForm init = new InitForm();
init.Show();
init.BringToFront();
comm = init.Start();
this.Opacity = 100;

Once it gets freed it shows both the forms and list box populated. It is behaving correctly in my opinion

this.Opacity = 0; Above line won't have any effect because UI thread will execute all the lines first then it will display the UI which means by the time UI shows something this.Opacity = 100; would have already been executed

    I want to display a small form when the program is ran. The InitForm 
is behind the main form. How do I bring it to front?

Why don't you set the Small Form as startup form and load the MainForm in load method of small form?

Upvotes: 0

Related Questions