VS 2019项目加载时运行资源生成器的扩展实现技术问询
Great question! Let's break this down into the two parts you asked:
1. Are there existing extensions to handle this?
From what I've researched, there isn't a mainstream Visual Studio extension built specifically for this exact workflow. That said, you don't necessarily need an extension to get the behavior you want—MSBuild configuration can handle both excluding generated designer files and triggering resource generation on project load in a lightweight way:
- To exclude
*.designer.csfrom your repo, mark them as generated in your project file and update your.gitignore:<ItemGroup> <EmbeddedResource Update="*.resx"> <Generator>ResXFileCodeGenerator</Generator> <LastGenOutput>%(Filename).designer.cs</LastGenOutput> </EmbeddedResource> <GeneratedFiles Include="*.designer.cs" /> <DefaultItemExcludes>$(DefaultItemExcludes);**/*.designer.cs</DefaultItemExcludes> </ItemGroup> - You can also force resource generation to run on project load by adding a custom MSBuild target (more on this below, even if you don't build an extension).
2. Which SDK classes/events to hook if building a custom extension?
If you want to build a dedicated extension, here are the key Visual Studio SDK points to target:
- Project Load Event Listener:
Use theIVsSolutionEvents3interface (specifically itsOnAfterOpenProjectmethod) to trigger your logic immediately after a project finishes loading. Register this event in your extension's package to get notified every time a project opens in the solution.
For more granular control over project load stages, look intoIVsProjectLoadEvents, which exposes events likeOnBeforeProjectLoadandOnAfterProjectLoadComplete. - Project File Traversal:
To scan the project for RESX files, use theMicrosoft.Build.Evaluation.Projectclass (reference the MSBuild assemblies in your extension) to load the project file, then iterate over itsItemscollection to filter forEmbeddedResourceitems with the.resxextension. Alternatively, use theIVsProjectCOM interface'sGetItemCountandGetItemAtmethods if you prefer working with native VS APIs. - Triggering Resource Generation:
You can either:- Call
ResGen.exedirectly via a process start (passing the RESX file paths as arguments), or - Trigger the built-in MSBuild
GenerateResourcetarget usingIVsBuildManagerAccessorto ensure compatibility with VS's build system and existing project settings.
- Call
As a quick alternative to building an extension, adding this MSBuild target to your project file will trigger resource generation on project load without any extra tools:
<Target Name="ForceResourceGenOnLoad" BeforeTargets="InitializeBuild;BeforeBuild"> <GenerateResource Sources="@(EmbeddedResource)" OutputFiles="@(EmbeddedResource->'%(RootDir)%(Directory)%(Filename).designer.cs')" StronglyTypedClassName="%(Filename)" StronglyTypedLanguage="C#" StronglyTypedNamespace="$(RootNamespace)" /> </Target>
内容的提问来源于stack exchange,提问作者James Lavery

