Search code examples
c#wpfwinformswebview2

How can I share the same WebView2 code, between WPF and WinForms projects?


I have developed utility source code to work with WebView2 component, and I want to use it in 2 different projects, one is WPF, the other WinForms.

The problem is that WebView2 asks for different "using", one for each project.

In the WPF class, I have to set the "using" this way:

using Microsoft.Web.WebView2.Wpf;   // NOTE!!!

namespace Utility
{
    public static class WebView2_Helper
    {
    ...
    (code here, using the WebView2 component)
    ...
    }
}

And for the WinForms, I have to create another file and duplicate all the code, just to change the "using"...:

using Microsoft.Web.WebView2.WinForms;   // NOTE!!!

namespace Utility
{
    public static class WebView2_Helper
    {
    ...
    (code here... same as above!)
    ...
    }
}

The code after the "using" is the same, in both cases.

In C/C++, a solution could be saving the common code to a file, and then include it inside both classes.

What should be the solution in C#?


Solution

  • If your utility is its own library you can define two different outputs, one for usage with WinForms and one for WPF.

    <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
    
      <PropertyGroup>
        <OutputType>Library</OutputType>
        <TargetFramework>net8.0-windows</TargetFramework>
      </PropertyGroup>
    
      <PropertyGroup Condition="'$(Configuration)'=='WPF'">
        <DefineConstants>WPF</DefineConstants>
        <UseWPF>true</UseWPF>
      </PropertyGroup>
    
      <PropertyGroup Condition="'$(Configuration)'=='WINFORMS'">
        <DefineConstants>WINFORMS</DefineConstants>
        <UseWindowsForms>true</UseWindowsForms>
      </PropertyGroup>
    
    </Project>
    

    Then in your code:

    namespace Utility
    {
        public static class WebView2_Helper
        {
    #if WPF
            using Microsoft.Web.WebView2.Wpf;
    #elif WINFORMS
            using Microsoft.Web.WebView2.WinForms;
    #endif
    
        }
    }