I tried many things to use OCX in WinUI3, but there was no way possible, and I tried to find executable code in the console, but there was only one way using System.Windows.Forms. Since System.Windows.Forms is not available in WinUI3, I tried the code below using Win32 API.
internal class Program
{
[DllImport("ole32.dll", PreserveSig = false)]
[return: MarshalAs(UnmanagedType.Interface)]
public static extern object CoCreateInstance([In] ref Guid clsid, [MarshalAs(UnmanagedType.Interface)] object punkOuter, int context, [In] ref Guid iid);
static void Main()
{
var guid1 = new Guid("A1574A0D-6BFA-4BD7-9020-DED88711818D");
var guid2 = new Guid("00000000-0000-0000-C000-000000000046");
var a = CoCreateInstance(ref guid1, null, 1, ref guid2);
var b = a as KHOpenAPILib.KHOpenAPI; // KHOpenAPILib.KHOpenAPI is an interface on the dll automatically created by the visual studio with tlbimp when adding com references.
b.CommConnect(); // E_UNEXPECTED
}
}
internal class Program
{
static void Main()
{
var guid1 = new Guid("A1574A0D-6BFA-4BD7-9020-DED88711818D");
var type = Type.GetTypeFromCLSID(guid1);
var a = Activator.CreateInstance(type);
var b = a as KHOpenAPILib.KHOpenAPI;
b.CommConnect(); // E_UNEXPECTED
}
}
However, as written in the annotation, E_UNEXPECTED occurs. Can you tell me the cause or any other way?
Even if I try the code below considering STA, the result is the same.
internal class Program
{
static void Main()
{
var thread = new Thread(Foo);
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Console.ReadKey();
}
}
I don't think you can do that, and it is not related to WinUI. Using OCXs takes more than just calling CoCreateInstance. Please look at https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.axhost?view=windowsdesktop-7.0. Try creating such a class yourself following the examples. I cannot be more specific, because I don't have access to your OCX.