从控制台的Windows窗体

时间:2009-10-26 20:03:14

标签: c# console winforms

我想使用C#从控制台生成Windows窗体。大致类似于display在Linux中,并修改其内容等。这可能吗?

4 个答案:

答案 0 :(得分:6)

您应该能够为System.Windows.Forms添加引用,然后就可以了。您可能还必须将STAThreadAttribute应用于应用程序的入口点。

using System.Windows.Forms;

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        MessageBox.Show("hello");
    }
}

...更复杂......

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

答案 1 :(得分:4)

是的,您可以在控制台中初始化表单。添加对System.Windows.Forms的引用,并使用以下示例代码:

System.Windows.Forms.Form f = new System.Windows.Forms.Form(); 
f.ShowDialog(); 

答案 2 :(得分:4)

常见答案:

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

替代方案(取自here),例如 - 如果您想要从主应用程序以外的线程启动表单:

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

答案 3 :(得分:1)

你可以试试这个

using System.Windows.Forms;

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

再见。