且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何自定义WPF项目的Main函数

更新时间:2022-09-13 11:11:12

原文:如何自定义WPF项目的Main函数

  与Winform项目不同,WPF项目的Main函数在项目生成的时候,系统自动在后台为我们生成。根据项目生成方式的不同,其文件位于obj/Debug/App.g.cs或者obj/Release/App.g.cs。
  那么,我们修改其中的Main函数,是否可以达到自定义Main函数的目的呢?
  答案是否定的,因为该文件在项目每次生成的时候,都会被重新生成并覆盖。
  
  那么,如何在WPF项目中自定义Main函数呢?
  
  1.自定义静态类Program(名称随便取)类如下:

namespace BarCodeSystem
{
    public static class Program
    {
        /// <summary>
        /// Application Entry Point.
        /// </summary>
        [System.STAThreadAttribute()]
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
        public static void Main()
        {
            /*
            ...
            这里可以写自己的代码!
            ...
            */
            BarCodeSystem.App app = new BarCodeSystem.App();//WPF项目的Application实例,用来启动WPF项目的
            app.InitializeComponent();
            app.Run();
        }
    }
}

  2.重新选择程序入口点:
  重新生成项目,会报如下错误,说明自定义Main函数成功被识别:
  如何自定义WPF项目的Main函数
  接下来,右键项目->属性->应用程序->启动对象,选择自定义的Main函数作为程序的入口即可:
  如何自定义WPF项目的Main函数
  选择好之后,重新生成项目即可!