Reputation: 20119
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?
Upvotes: 5
Views: 14985
Reputation: 8015
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());
}
Upvotes: 4
Reputation: 136391
You can try this
using System.Windows.Forms;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MyForm());
}
Bye.
Upvotes: 1
Reputation: 22443
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();
}
}
Upvotes: 6
Reputation: 68687
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();
Upvotes: 4