如何改变一个C#控制台项目到Windows窗体应用程序项目?项目、窗体、控制台、应用程序

2023-09-03 20:46:58 作者:老阿姨也有少女心

创建一个C#控制台项目,其中包含一个控制台类(Program.cs中)。我添加了一个表格(Main.cs)到项目中。

created a c# console project, which contains a console class (program.cs). i added a form (Main.cs) to the project.

我想要做的以下事情之一与我的项目  1. 项目更改为Windows窗体应用程序,我可以将其更改为Windows窗体应用程序,而无需创建一个新的项目。  2. 设置主类作为启动对象。经过应用程序选项卡,在属性窗口。主类是不是在启动对象列表。

I want to do one of the below things with my project 1. Change the project to a Windows Form Application,can i change it to a Windows Form Application without creating a new project. 2. Set Main class as the startup object. Checked 'Application' tab in the properties window. The main class it not in the Startup object list.

推荐答案

东西,你必须做的:

项目+属性,应用程序选项卡,更改输出类型为Windows应用程序 项目+添加引用,选择至少System.Windows.Forms的和System.Drawing中 找到在Program.cs中源$ C ​​$ C文件中的Main()方法。给它的[STAThread]属性。

重写主()方法是这样的: Project + Properties, Application tab, change Output Type to "Windows Application" Project + Add Reference, select at least System.Windows.Forms and System.Drawing Locate your Main() method in the Program.cs source code file. Give it the [STAThread] attribute.

Rewrite the Main() method to look like this:

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

更改YourMainForm到您的窗体类的名称。打捞现有的code在main()方法是将可能是痛苦位。运行()调用后,你不能离开它,该调用不会返回,直到用户关闭你的主要形式。

Change "YourMainForm" to the name of your form class. Salvaging your existing code in the Main() method is what will probably be the painful bit. You cannot leave it after the Run() call, that call won't return until the user closes your main form.