If you are about to write another p/invoke (Win32 calls) to access existing Windows, Controls,...you should consider switching to UI Automation framework, which provides programmatic access to most user interface (UI) elements on the desktop, by writing managed code. Some time ago I wrote an article about UI Automation, have a look at: http://www.codeproject.com/KB/WPF/WPF_UI_Automation.aspx
In this post, I'll try to compare two ways of implementing Windows automation applications, by using unmanaged code (Win32 interoperability) and by using the UI Automation framework (managed code).
OK, let's take a simple example. Suppose we want to write a piece of code that gets the active window and some details about this window.
Instead of writing Win32 calls for GetWindow, GetWindowRect, different structures, etc, with UI Automation we can write simple managed code to accomplish the same task.
Basically, we just need to get AutomationElement.FocusedElement and this will provide us useful informations about the focused control which might be a simple control(Button, TextBox, etc) or a Window. Let's assume that the returned FocusedControl is a Textbox, a not a Window; we still can get the parent Window of that control, by getting first the ProcessId property. Based on the process Id, we can create an instance of Process class and access process.MainWindowHandle, to get the Window handle. Now, based on the Window handle, we can call the static method AutomationElement.FromHandle() and you'll get the AutomationElement for the window. To get the window bounds, just call windowElement.Current.BoundingRectangle and you'll obtain a Rect object. After that you may use the bounds to capture the window, etc.
AutomationElement controlElement = AutomationElement.FocusedElement;
if (controlElement != null && controlElement.Current.ControlType != ControlType.Window)
Process process = Process.GetProcessById(controlElement.Current.ProcessId);
AutomationElement windowElement = AutomationElement.FromHandle(process.MainWindowHandle);
if (windowElement != null)
Rect r = windowElement.Current.BoundingRectangle;
Another example would be to get the user control based on the cursor position. So we want to find a managed solution for WindowFromPoint Win32 function. We can accomplish this without writing Interop code, by calling and passing a Point to AutomationElement.FromPoint();