[英]Windows form from console
I would like to spawn a Windows form from the console using C#. 我想使用C#从控制台生成Windows窗体。 Roughly like
display
does in Linux, and modify its contents, etc. Is that possible? 大致类似于Linux中的
display
,并修改其内容等。这可能吗?
You should be able to add a reference for System.Windows.Forms and then be good to go. 您应该能够为System.Windows.Forms添加引用,然后就可以了。 You may also have to apply the STAThreadAttribute to the entry point of your application.
您可能还必须将STAThreadAttribute应用于应用程序的入口点。
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();
}
}
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的引用,并使用以下示例代码:
System.Windows.Forms.Form f = new System.Windows.Forms.Form();
f.ShowDialog();
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());
}
You can try this 你可以试试这个
using System.Windows.Forms;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new MyForm());
}
Bye. 再见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.