views:

78

answers:

2

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)

+2  A: 

With IE what you're drawing on is the parent window and IE8 has the WS_CLIPCHILDREN window style set. What you need to do is to descent the window hierarchy and figure out exactly which child you want to render on and then go to town on that window instead.

Aaron
WS_CLIPCHILDREN is not the problem with IE8.
Franci Penov
How do I traverse the IE8 window hierarchy?
Joel Harris
To traverse the hierarchy you need to use the EnumChildWindows() GDI function (or FindWindowEx(), etc). You may want to use Spy++ first to look at the IE8 window and compare the handle to the value you're getting to determine if the problem is what I'm describing or what @Franci Penov is describing.
Aaron
+1  A: 

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:

  • it does not have a top-level window;
  • nothing guarantees you that the current visible tab belongs to this process.\

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.

Franci Penov