In this post I’ll show how you can use COM type libraries in a .NET Core Windows Forms project. Sometimes you need to add a reference to a COM type library, for example, let’s say you want to add a reference to
SHDocVw to use advanced features of web browser which are not exposed in
WebBrowser .NET control. The common approach which we used to do in Visual Studio Windows Forms .NET Framework project was doing so using Add Reference, but in a .NET CORE Windows Forms project using Visual Studio 2019 (Version 16.2.1) if you try to a reference of a COM type library to the project, when you open Reference Manager window, you can not see any COM tab in the window.
Please note: The Reference Manager Window in above image belongs to Visual Studio 2019 (Version 16.2.1) and regarding to this GitHub thread, future release of VS 2019 will be fixed to contain
COMtab. While you still can use this workaround for all type libraries, but in case the COM tab exists, it’s preferred to add the reference from there.
So how can you add a reference to a COM library in .NET CORE Windows Form Project?
You can always use
tlbimp.exe to convert the type definitions of COM type library into equivalent definitions in .NET assembly.
You can find
shdocvw.dll in one of the following locations in your system:
To add a reference to
mshtml, follow these steps:
- Open Developer Command Prompt for VS 2019
tlbimp.exe "c:\windows\SysWOW64\mshtml.tlb" "c:\MSHTML.dll"
- Wait until the command run successfully after a few warnings, Then it will show TlbImp : Type library imported to mshtml.dll
- In your Visual Studio Windows Forms .NET CORE Project, right click on Dependencies and click on Add Reference. Select Browse tab and click on Browse button and choose
"c:\MSHTML.dll"file which you created in the previous step.
- After adding the reference, right click on the
MSHTML.dllwhich has been added under Assemblies. Choose Properties and in the properties window, set
Embed Interop Typesto
You can do the same for
shdocvw.dll as well and export it to
SHDocVw.dll using the steps described above.
Then you can use all classes and interfaces inside those libraries.