如何将C#控制台项目更改为Windows窗体应用程序项目?

3
我创建了一个C#控制台项目,其中包含一个控制台类(program.cs)。我向该项目添加了一个窗体(Main.cs)。
我想要在我的项目中执行以下操作之一: 1. 将项目更改为Windows窗体应用程序。我能否在不创建新项目的情况下将其更改为Windows窗体应用程序? 2. 将Main类设置为启动对象。在属性窗口中勾选“应用程序”选项卡。但是主类不在启动对象列表中。
4个回答

7

你需要完成以下任务:

  1. Project + Properties, Application tab, change Output Type to "Windows Application"
  2. Project + Add Reference, select at least System.Windows.Forms and System.Drawing
  3. Locate your Main() method in the Program.cs source code file. Give it the [STAThread] attribute.
  4. Rewrite the Main() method to look like this:

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

将“YourMainForm”更改为您的表单类名称。挽救现有代码中的Main()方法可能是痛苦的部分。您不能在Run()调用后留下它,该调用直到用户关闭您的主窗体才会返回。


3
在项目属性中,将输出类型从 控制台应用程序 改为 Windows 应用程序

2
  1. 将项目更改为Windows窗体应用程序 前往项目属性->“应用程序”选项卡->“输出类型”下拉框,选择“Windows应用程序”。

  2. 将主类设置为启动对象 只要您有一个包含静态方法Main()的单个类,就不必设置启动对象。 要运行Windows应用程序,您必须实现一个包含调用Application.Run()的方法Main。您可以使用新项目向导创建Windows Forms项目以查看示例。


1

alt text


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接