从控制台的Windows窗体
我想使用C#从控制台生成Windows窗体。 大致类似于Linux中的display
,并修改其内容等。这可能吗?
您应该能够为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(); } }
是的,您可以在控制台中初始化表单。 添加对System.Windows.Forms的引用并使用以下示例代码:
System.Windows.Forms.Form f = new System.Windows.Forms.Form(); f.ShowDialog();
常见答案:
[STAThread] static void Main() { Application.Run(new MyForm()); }
替代方案(取自此处 ),例如 – 您想要从主应用程序以外的线程启动表单:
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()); }
你可以试试这个
using System.Windows.Forms; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new MyForm()); }
再见。