buddy
buddy

Reputation: 428

How to open a second Form as dialog when the first Form is already loaded?

I have two forms: Form1 and Form2.

I want to show Form2 as dialog when Form1 has been loaded. I mean when Form1 is loaded and visible to the user, then Form2 is showed as dialog.

With the Form1_Load event it first show the Form2 as dialog and then show Form1.

How can I first show Form1 and then Form2 as dialog?

Upvotes: 1

Views: 20634

Answers (3)

wertyk
wertyk

Reputation: 408

You can load the second form in event Form1 Validated:

public Form1()
{    
     this.Validated += Form1_Validated;
     InitializeComponent();
}
private void Form1_Validated(object sender, EventArgs e)
{
     Form2 myForm2 = new Form2();
     myForm2.Show();
}

Upvotes: 0

S2S2
S2S2

Reputation: 8512

Use the Shown event of form1 to load the form2 as follows:

void form1_Shown(object sender, EventArgs e)
{
    Form2 form2 = new Form2();
    form2.Show();
}

That way first form1 will be displayed and raise the Shown event and inside Shown event, form2 will be loaded and displayed.

Upvotes: 5

corylulu
corylulu

Reputation: 3499

This to launch Form1, then Form2

public Form1()
{    
     this.Load+= Form1_Load;
     InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
     Form2 myForm2 = new Form2();
     myForm2.Show();
}

or to do without loading Form1 first, and forcing them into Form2 first.

public Form1()
{    
     Form2 myForm2 = new Form2();
     myForm2.ShowDialog(); 
     //ShowDialog() will prevent actions from happening on this 
     //thread until Form2 is closed.

     InitializeComponent();
}

if you just want to start Form2 first, just modify the Program.cs

static void Main(string[] args)
{

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    if (args.Length == 0) //if no command line arguments, run Form1
    {
        Application.Run(new Form1());
    }
    else //if command line arguments exist, run Form2
    {
        Application.Run(new Form2());
    }

}

Upvotes: 0

Related Questions