Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Window instance from Window Handle

Tags:

c#

.net

wpf

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

foreach (ProcessModule module in process.Modules)
{
  if (module.ModuleName.Contains("PresentationFramework.dll") || module.ModuleName.Contains("PresentationFramework.ni.dll"))
  {
    IntPtr window = process.MainWindowHandle;
  }
}

But I want to get the Window instance from this handler. Is it possible?

Any quick idea please?

like image 882
Jawahar Avatar asked Feb 25 '11 11:02

Jawahar


2 Answers

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.

like image 78
Pavlo Glazkov Avatar answered Oct 03 '22 10:10

Pavlo Glazkov


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.

like image 43
Tergiver Avatar answered Oct 03 '22 10:10

Tergiver