Search code examples
c#dllreflection

Show a Window from the instance of a Dll


I am trying to open the window which is inside a Dll. I created an instance of the DLL and I and getting the below error.

Unable to cast object of type 'MyDll.CLSFormShow' to type 'System.Windows.Window'.

Thanks in advance.

Code

string connString;
connString = "Hello World";

string strDllPath = "C:\\MyDll\\MyDll\\bin\\Debug\\netcoreapp3.1\\MyDll.dll";
string assemblyName = string.Format(strDllPath, new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName);

string strNsCn = "MyDll.CLSFormShow";
object[] paramObj = new object[1];
paramObj[0] = connString;

Assembly DLL = Assembly.LoadFrom(strDllPath);
Type classType = DLL.GetType( strNsCn);
object classInst = Activator.CreateInstance(classType, paramObj);
Window dllWinForm = (Window)classInst;
dllWinForm.ShowDialog();
type here

On executing the code, I am getting the error Unable to cast object of type 'MyDll.CLSFormShow' to type 'System.Windows.Window'.


Solution

  • It seems like you are trying to cast an object of type 'MyDll.CLSFormShow' to type 'System.Windows.Window', but they are not compatible types. The 'CLSFormShow' class is not derived from the 'System.Windows.Window' class, so you cannot cast it to this type.

    To open the window that is inside the DLL, you need to use the appropriate type or base class of the window. You can try casting the object to the base class of the window, or if you know the specific type of the window, you can cast it to that type.

    // create an instance of the DLL
    MyDll.CLSFormShow myForm = new MyDll.CLSFormShow();
    
    // check if the object is of the expected type
    if (myForm is System.Windows.Window)
    {
        // cast the object to the Window type and open the window
        System.Windows.Window myWindow = (System.Windows.Window)myForm;
        myWindow.ShowDialog();
    }
    else
    {
        // handle the error condition
        Console.WriteLine("Error: object is not a Window");
    }