Running a a form from a form

aewarnick

Senior Contributor
Joined
Jan 29, 2003
Messages
1,031
Running a a form from a form
I have 2 classes:

public class Form1 : System.Windows.Forms.Form
public class Form3 : System.Windows.Forms.Form
--------------------------------------------
Main() starts Form3 (simple yes, no label):

static void Main()
{
Application.Run(new Form3());
}
--------------------------------------------
For the YES button I have the other form I want to run and close the Form3.

private void YES_Click(object sender, System.EventArgs e)
{
Application.Run(new Form1);
Application.Exit();
}
--------------------------------------------
When I run this and press YES an error box pops up that says:

An unhandled exception of type 'System.InvalidOperationException' occurred in system.windows.forms.dll

Additional information: It is invalid to start a second message loop on a single thread. Use Application.RunDialog or Form.ShowDialog instead.
--------------------------------------------
When I try to use Form.ShowDialog it won't compile and says it needs an object.
When I try to use Application.RunDialog it says it is unaccessable due to its protection level.

What should I do?
 
Try doing this:
C#:
Form1 frm = new Form1;

frm.Show(); //or frm.ShowDialog(), depending on if you want it to be modal or not.
 
You forgot the () I think, and with them it works.

Also, It ends as soon as it opens when I have

Application.Exit();

there. How can I close the Form3 only?

And, what is the difference between Show and ShowDialog?
 
ShowDialog restricts focus to the form you are showing until it is
closed, while Show doesn't.

Use
C#:
this.Close();
to close the current form. If you want to
close the form from within another form, you'll need to keep the
object you used to initialize the form and use the Close method on it.
 
When I use this.Close(); it does the same thing as closing the whole application.

private void YES_Click(object sender, System.EventArgs e)
{
YES.Enabled=false;
Form1 frm1 = new Form1();
frm1.Show();
this.Close();
}

I also tried creating a Form3 object in Form1 but the frm3.Close(); did nothing at all.

I think the forms are connected too tightly somehow because when I close Form3 where main is I close both. ShowDialog(); works but it does not close the Form3 until Form1 is closed.
Is there any way around that, so that I can immediately close Form3?
 
Last edited:
Ah, I see. You are trying to close the form which the application is
running off of. I'm not sure how to get around it...

You might try changing the Application.Run(new Form3());
line to Application.Run(); and then attempting to open the
form manually using the method I showed you above.

[edit]Make sure to call Application.Exit(); to close the program![/edit]
 
You may want to read up on Application.Run. Since you're passing the Run method a form, the application exits when that form closes. There are a couple of other options - check out the help file to get a full list.

Normally, you would only have one "main" form that Application.Run will run. It might be an MDI form or it might be an SDI application that creates other forms, such as splash screens, toolbar windows, etc. In these scenarios, you'll use Application.Run(new FormX()).

If you want to have independant forms, you can. Just create a form and .Show() it, then call Application.Run() with no parameter. You MUST call Application.Exit() at some point to shut down the application though. Closing the last form doesn't do this - you'll have to know when the last form is closing and call Application.Exit(). You can often do this in your last form's Closed event.

Here's some code snippets:
C#:
// In Form1:
[STAThread]
static void Main() 
{
	Form1 f = new Form1();
	f.Show();
	// The following runs until Application.Exit() or Application.ExitThread()
	Application.Run();
}

// In Form1's button1_click event:
private void button1_Click(object sender, System.EventArgs e)
{
	Form2 f = new Form2();
	f.Show();
	this.Close();
}

// In Form2's Closed event:
private void Form2_Closed(object sender, System.EventArgs e)
{
	Application.Exit();
}

If you're cutting and pasting this code, make sure you actually wire up the events, don't just paste in the functions :)

-Nerseus
 
But the problem is that I do not want the first window to stay in the tray (it is the one with Main() in it. So maybe I can't close it) when I show and run the second window.

I know what might fix it!!!!
I will just put Main in the other form!!!!!!!!
I'll post back.
 
Very frustrated!!
Here is what I have got:

//form1:
static void Main()
{
Form3 frm3=new Form3();
frm3.Show();
Application.Run();
}

private void Form1_Closed(object sender, System.EventArgs e)
{
Application.Exit();
}



//form3:
private void YES_Click(object sender, System.EventArgs e)
{
YES.Enabled=false;
Form1 frm1 = new Form1();
frm1.Show();
this.Close();
}


It never clears out of memory!!! Please help!
 
If you want Form3 to clear out of memory then you must change:
C#:
//form3:
private void YES_Click(object sender, System.EventArgs e)
{
    YES.Enabled=false;
    Form1 frm1 = new Form1();
    frm1.Show();
    this.Dispose();
}

You would want to use this.Close() if you planned on reopening Form3 again later. Dispose will wipe it out of memory.

-Nerseus

edited: forgot you were opening Form3 first :)
 
Thank you. I tried it and it closed but never took it out of memory when the program was completely closed down. I always still had to do the same thing: ctrl alt delete.
This is in both forms becuse VS put it there:

protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

I tried removing it but that did not fix the problem either.
 
Ack! Don't mess with the default form's Dispose method unless you need to (and you don't need to) :)

Can you upload your project for us to see? It seems like it should be working.

-Nerseus
 
Here is where you do:

Move your Sub Main over to Form3, and set your project's
startup form to Form3. Then, change the Sub Main method to this:
C#:
static void Main() 
{
	Form3 frm3 = new Form3();
	frm3.Show();

	Application.Run();
}
Then, in Form1's Closed event, add this:
Visual Basic:
Application.Exit();
It should work now. Click 'YES' and it will open your Form1, and
then closing that form will end the program.

BTW, Nerseus, WinZip will open CABs, and perhaps Windows will
too?

[edit]Oops, accidentally used VB tags; switched to C#[/edit]
 
Last edited:
If you have win9x it is in:

C:\Windows\Command\Extract.exe

Hold in Shift and right click on the cab file
Go to open with and find the Extract program.
 
I have WinXP and Win2000 but neither use WinZip - I use the built-in compresser of WinXP but it doesn't understand CAB files for some reason (or at least mine wasn't opening it).

Couldn't find extract at that location for XP. I know it's out there, just never remember where it is.

Thanks for helping out, Volte :)

-Nerseus
 
No problem. :)

Anyway,

C:\WINNT\SYSTEM32\EXTRAC32.EXE

It appears that's where it is for me. I don't know exactly how to use
it, but Open With... calls it a "CAB Extraction Utility", so I assume that's
what aewarnick is speaking of.
 
Here is what I have pop up first:

Code:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace WindowsApplication2
{
	/// <summary>
	/// Summary description for Form3.
	/// </summary>
	public class Form3 : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button YES;
		private System.Windows.Forms.Button NO;
		private System.Windows.Forms.Button SureButton;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

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

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.YES = new System.Windows.Forms.Button();
			this.NO = new System.Windows.Forms.Button();
			this.SureButton = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// YES
			// 
			this.YES.Location = new System.Drawing.Point(24, 80);
			this.YES.Name = "YES";
			this.YES.Size = new System.Drawing.Size(80, 40);
			this.YES.TabIndex = 0;
			this.YES.Text = "YES";
			this.YES.Click += new System.EventHandler(this.YES_Click);
			// 
			// NO
			// 
			this.NO.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.NO.ForeColor = System.Drawing.Color.Brown;
			this.NO.Location = new System.Drawing.Point(152, 80);
			this.NO.Name = "NO";
			this.NO.Size = new System.Drawing.Size(80, 40);
			this.NO.TabIndex = 1;
			this.NO.Text = "NO";
			this.NO.Click += new System.EventHandler(this.NO_Click);
			// 
			// SureButton
			// 
			this.SureButton.Font = new System.Drawing.Font("Georgia", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.SureButton.ForeColor = System.Drawing.SystemColors.ActiveCaption;
			this.SureButton.Name = "SureButton";
			this.SureButton.Size = new System.Drawing.Size(256, 56);
			this.SureButton.TabIndex = 2;
			this.SureButton.Text = "Sure you want to go through with this?";
			this.SureButton.Click += new System.EventHandler(this.SureButton_Click);
			// 
			// Form3
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(11, 22);
			this.ClientSize = new System.Drawing.Size(256, 134);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.SureButton,
																		  this.NO,
																		  this.YES});
			this.Font = new System.Drawing.Font("Georgia", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.ForeColor = System.Drawing.Color.Red;
			this.Name = "Form3";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Make Sure";
			this.Load += new System.EventHandler(this.Form3_Load);
			this.ResumeLayout(false);

		}
		#endregion

		private void YES_Click(object sender, System.EventArgs e)
		{
			YES.Enabled=false;
			Form1 frm1 = new Form1();
			frm1.Show();
			this.Dispose();
		}
		
		private void NO_Click(object sender, System.EventArgs e)
		{			
			NO.Enabled=false;
			MessageBox.Show("BYE THEN", "FAREWELL");
			Application.Exit();
		}

		private void SureButton_Click(object sender, System.EventArgs e)
		{
			MessageBox.Show("Wut yu doin!!", "!!!!!!!");
			int x=5, y=2;
			for (; x != y; ++y) MessageBox.Show("not = "+ y);
			MessageBox.Show(""+y);
		}

		private void Form3_Load(object sender, System.EventArgs e)
		{
		
		}
		
		
	}
}
 
Back
Top