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 = pro开发者_如何学编程cesses[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)
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.
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.
精彩评论