views:

232

answers:

4

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?

+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
Can I get some comments on the downmods?
Yuriy Faktorovich
Why was this downvoted? It may not be great practice, but it's definitely possible.
Jon Seigel
Will this work without the STAThread attribute?
Philip Wallace
+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
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
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
What is the opinion on posting half answers? I've seen Marc do it several times, so I figured it was normal.
Yuriy Faktorovich
+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
A: 

You can try this

using System.Windows.Forms;

[STAThread]
static void Main() 
{
    Application.EnableVisualStyles();
    Application.Run(new MyForm()); 
}

Bye.

RRUZ
+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