Get Window instance from Window Handle

后端 未结 2 696
傲寒
傲寒 2021-02-19 09:06

I am able get a Window handle from running applications using the following code.

foreach (ProcessModule module in process.Modules)
{
  if (module.ModuleName.Con         


        
相关标签:
2条回答
  • 2021-02-19 09:51

    In a WPF application (or WinForms) there are two 'objects' (that is blocks of memory containing information) to a 'window':

    1. The system window object.
    2. The managed objects that 'wraps' the system object.

    Access to the system window object is provided through the window handle (typeof HWND in unmanaged code, IntPtr in managed code). Given a window handle, which you already obtained, you can manipulate that window using the Window API methods. You can use p/invoke for this.

    Access to the managed object, which resides in the heap of the process (or AppDomain in the case of a managed process) is forbidden. This memory is 'protected' from other processes(1).

    The only way that objects can be shared between processes (or AppDomains) is through marshalling which is a cooperative effort on the part of both processes. This applies even to many of the Win32 API methods when accessing a window in another process. Not all access is possible without custom marshalling.

    Note that unlike WinForms, WPF does not (normally) use system windows for controls. If your aim is to manipulate the visual tree in another WPF process/domain, you're simply out of luck unless that process provides some sort of Automation interface.

    (1) While it is possible to read the raw memory of another process, objects on a managed heap are moving targets. One could never even find them, even if you could somehow suspend the garbage collecting thread of that process.

    0 讨论(0)
  • 2021-02-19 09:56

    Try the following:

    IntPtr handle = process.MainWindowHandle;
    
    HwndSource hwndSource = HwndSource.FromHwnd(handle);
    
    Window = hwndSource.RootVisual as Window;
    

    Update:

    But this will work only inside the same AppDomain, because otherwise it would mean that you could share an object across different AppDomains and even processes, which is obviously impossible.

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