C# Reflection: Is it possible to find an instance of an object at runtime?

前端 未结 7 1063
说谎
说谎 2020-12-07 01:53

I\'m wondering if it\'s possible to use reflection to locate an object at runtime? This is more of an experiment than a practical requirement.

I\'ve used the .GetTyp

相关标签:
7条回答
  • 2020-12-07 02:48

    If you are just experimenting and trying to locate the Main Form from your DLL you could do:

    //get the current process
    System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
    
    //get its main windows handle (only works, if the form is already created)
    IntPtr hWnd = p.MainWindowHandle;
    
    //locate the form by its native handle
    System.Windows.Forms.Form f = System.Windows.Forms.Form.FromHandle(hWnd) as System.Windows.Forms.Form;
    

    Have just tested that for dependent assemblys, not for dynamically loaded ones. But it could be worth a try.

    For the general issue of locating a specific instance, the question has already been answerd.

    0 讨论(0)
提交回复
热议问题