Search code examples
c#visual-studiowinformswindows-forms-designertarget-platform

Read the project's target platform during design time in C#


Is it possible to detect if a winform project's target platform is set to AnyCPU using C# programming language during design mode?

For example, creating a button control that, when clicked, will determine if the project's target platform is set to AnyCPU, x86 or x64?

This should be detected while in design mode by a hosted control, e.g. a button click determining the target platform of the project it is being used in.

The language of use is C#.


Solution

  • You can add a reference to EnvDTE and add such a property to your control:

    [EditorBrowsable(EditorBrowsableState.Never)]
    public string TargetPlatform
    {
        get
        {
            if (!DesignMode)
                return null;
    
            var host = (IDesignerHost)Site.GetService(typeof(IDesignerHost));
            var dte = (EnvDTE.DTE)host.GetService(typeof(EnvDTE.DTE));
            var project = dte.ActiveSolutionProjects[0];
            return project.ConfigurationManager.ActiveConfiguration.Properties
                          .Item("PlatformTarget").Value;
        }
    }
    

    Note: The answer is a PoC showing the solution works. For a real world scenario, it should be a design-time only property of the designer of the control in a separate assembly. Then you don't need to distribute additional assemblies.

    Also the [Designer] attribute should use name of the types rather than type itself. It's the same way that windows forms designers work. You don't need to distribute additional design-time assemblies along with your application, however as part of the nuget package or VSIX of your control installer, they should be distributed to work in VS.