Hello.
I would like to spawn a Windows form from the console using C#. Roughly like display
does in Linux, and modify its contents, etc. Is that possible?
views:
232answers:
4
+1
A:
Yes, you can initialize a form in the Console. Add a reference to System.Windows.Forms and use the following sample code:
System.Windows.Forms.Form f = new System.Windows.Forms.Form();
f.ShowDialog();
Yuriy Faktorovich
2009-10-26 20:04:59
Can I get some comments on the downmods?
Yuriy Faktorovich
2009-10-26 20:09:26
Why was this downvoted? It may not be great practice, but it's definitely possible.
Jon Seigel
2009-10-26 20:09:58
Will this work without the STAThread attribute?
Philip Wallace
2009-10-26 20:15:41
+1 because it works without the STAThread attribute. Maybe it could potentially have other issues without the attribute, but that does not make it deserving of any down-votes. If there's a problem, better to mention it in a comment and let the poster fix it.
MusiGenesis
2009-10-26 20:18:42
This page (and others) recommends you either use the STAThread attribute, or create the form in a separate thread and manually set the AppartmentState: http://blogs.msdn.com/jfoscoding/archive/2005/04/07/406341.aspx
Philip Wallace
2009-10-26 20:22:44
He got the downvotes before he extended his answer. But it would still be nice if people would say why instead of just down voting.
Matthew Whited
2009-10-26 20:26:48
What is the opinion on posting half answers? I've seen Marc do it several times, so I figured it was normal.
Yuriy Faktorovich
2009-10-26 20:48:59
+5
A:
You should be able to add a reference for System.Windows.Forms and then be good to go. You may also have to apply the STAThreadAttribute to the entry point of your application.
using System.Windows.Forms;
class Program
{
[STAThread]
static void Main(string[] args)
{
MessageBox.Show("hello");
}
}
... more complex ...
using System.Windows.Forms;
class Program
{
[STAThread]
static void Main(string[] args)
{
var frm = new Form();
frm.Name = "Hello";
var lb = new Label();
lb.Text = "Hello World!!!";
frm.Controls.Add(lb);
frm.ShowDialog();
}
}
Matthew Whited
2009-10-26 20:07:55
A:
You can try this
using System.Windows.Forms;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MyForm());
}
Bye.
RRUZ
2009-10-26 20:11:42
+1
A:
The common answer:
[STAThread]
static void Main()
{
Application.Run(new MyForm());
}
Alternatives (taken from here) if, for example - you want to launch a form from a thread other than that of the main application:
Thread t = new Thread(new ThreadStart(StartNewStaThread));
// Make sure to set the apartment state BEFORE starting the thread.
t.ApartmentState = ApartmentState.STA;
t.Start();
private void StartNewStaThread() {
Application.Run(new Form1());
}
.
Thread t = new Thread(new ThreadStart(StartNewStaThread));
t.Start();
[STAThread]
private void StartNewStaThread() {
Application.Run(new Form1());
}
Philip Wallace
2009-10-26 20:47:48