I have the following code which draws a square on the main window of another process:
private void DrawOnWindow(string processname)
{
IntPtr winhandle = GetWindowHandle(processname);
Graphics grph = Graphics.FromHwnd(winhandle);
grph.DrawRectangle(Pens.Red, 10, 10, 100, 100);
}
private IntPtr GetWindowHandle(string windowName)
{
IntPtr windowHandle = IntPtr.Zero;
Process[] processes = Process.GetProcessesByName(windowName);
if (processes.Length > 0)
{
for (int i = 0; i < processes.Length; i++)
{
if (processes[i].MainWindowHandle.ToInt32() > 0)
{
windowHandle = processes[i].MainWindowHandle;
break;
}
}
}
return windowHandle;
}
This works when I pass “firefox” to the DrawOnWindow method, but it does not work when I pass “iexplore” and I don’t understand why. What do I need to do to get this to work on internet explorer? (IE8)
IE8 has one top-level process, which contains the main window and draws the frame, address bar, and other controls in it. t also has several child processes, which own one or more tabs and their corresponding windows.
Your code will return the window handle for the top-level window of the last Iexplore process. However, if that process happens to be a child window, there are two problems:
You need to modify your code and special-case it for IE to accommodate for the specifics of the IE process/window hierarchy.
Btw, if you decide to draw on Chrome, you will have similar problems, as they also do similar tricks with multiple processes and window hierarchy that spans across these processes.