WPF - 关闭 App.g.cs 中 Main 的自动生成

swiftAI

1个回答

写回答

13125807128

2025-08-27 22:30

+ 关注

AI
AI

如何关闭 WPF 中 App.g.cs 中 MAIn 方法的自动生成

在 WPF (Windows Presentation Foundation) 开发中,App.g.cs 文件是自动生成的一个文件,其中包含了一个主入口方法 MAIn。这个方法是应用程序的启动点,它负责初始化应用程序并创建主窗口。然而,在某些情况下,我们可能希望手动控制应用程序的启动过程,而不使用自动生成的 MAIn 方法。本文将介绍如何关闭 App.g.cs 中 MAIn 方法的自动生成,并提供相应的案例代码。

关闭 App.g.cs 中 MAIn 方法的自动生成可以通过修改项目文件来实现。首先,打开项目文件(通常是以 .csproj 或 .vbproj 结尾的文件),找到以下代码:

XML

<Compile Include="App.xaml.cs">

<DependentUpon>App.xaml</DependentUpon>

<SubType>Code</SubType>

</Compile>

将其修改为:

XML

<Compile Include="App.xaml.cs">

<DependentUpon>App.xaml</DependentUpon>

<SubType>Code</SubType>

<Generator>MSBuild:Compile</Generator>

</Compile>

这样一来,编译器将不再自动生成 App.g.cs 文件,也就不会包含 MAIn 方法了。接下来,我们需要手动添加一个自定义的 MAIn 方法来替代自动生成的 MAIn 方法。

在 App.xaml.cs 文件中添加以下代码:

csharp

using System;

using System.Windows;

namespace YourNamespace

{

public partial class App : Application

{

[STAThread]

public static void MAIn()

{

// 自定义的 MAIn 方法代码

// ...

// 启动应用程序

var app = new App();

app.InitializeComponent();

app.Run();

}

}

}

在这个自定义的 MAIn 方法中,你可以编写任何你希望在应用程序启动时执行的代码。例如,你可以初始化一些全局变量、注册一些事件处理程序等。然后,通过创建一个新的 App 对象并调用其 InitializeComponent() 和 Run() 方法来启动应用程序。

现在,当你构建和运行应用程序时,它将使用你添加的自定义 MAIn 方法作为启动点,而不再使用自动生成的 MAIn 方法。

案例代码

下面是一个简单的案例代码,演示了如何关闭 App.g.cs 中 MAIn 方法的自动生成:

XML

<!-- MyProject.csproj -->

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>

<OutputType>WinExe</OutputType>

<TargetFramework>net5.0-windows</TargetFramework>

</PropertyGroup>

<ItemGroup>

<Compile Include="App.xaml.cs">

<DependentUpon>App.xaml</DependentUpon>

<SubType>Code</SubType>

<Generator>MSBuild:Compile</Generator>

</Compile>

</ItemGroup>

</Project>

csharp

// App.xaml.cs

using System;

using System.Windows;

namespace MyNamespace

{

public partial class App : Application

{

[STAThread]

public static void MAIn()

{

// 自定义的 MAIn 方法代码

Console.WriteLine("Hello, World!");

// 启动应用程序

var app = new App();

app.InitializeComponent();

app.Run();

}

}

}

在这个案例中,我们关闭了 App.g.cs 中 MAIn 方法的自动生成,并添加了一个简单的自定义 MAIn 方法,它会在应用程序启动时输出 "Hello, World!"。

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号