Windows form from console

馋奶兔 提交于 2020-01-11 03:02:05

问题


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:


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();
    }
}



回答2:


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(); 



回答3:


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()); 
} 



回答4:


You can try this

using System.Windows.Forms;

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

Bye.



来源:https://stackoverflow.com/questions/1627014/windows-form-from-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!