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?
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.
In a WPF application (or WinForms) there are two 'objects' (that is blocks of memory containing information) to a 'window':
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With