I am trying to draw some lines and rectangles on an existing window. I found the following code to draw on the desktop that works perfectly fine.
class Drawing {
[DLLImport("User32.dll")]
static extern IntPtr GetDC(IntPtr hWnd);
public static void draw(Rectangle r, Brush b, IntPtr hWnd) {
using(Graphics g = Graphics.FromHdc(hwnd)) {
g.DrawRectangle(b, r);
}
}
}
Drawing.draw(new Rectangle(0, 0, 40, 80), Brushes.Red, Drawing.GetDC(IntPtr.Zero));
This is the code how I modified it to draw on a specific window.
class Drawing {
public static IntPtr WinGetHandle(string wName) {
foreach (Process pList in Process.GetProcesses())
if (pList.MainWindowTitle.Contains(wName))
return pList.MainWindowHandle;
return IntPtr.Zero;
}
public static void draw(Rectangle r, Brush b, IntPtr hwnd) {
using(Graphics g = Graphics.FromHwnd(hwnd)) {
g.DrawRectangle(p, r);
}
}
}
Drawing.draw(new Rectangle(0, 0, 40, 80), Brushes.Red, Drawing.WinGetHandle("DrawingWindow"));
With this code nothing happens and in some cases it throws OutOfMemoryException and crashes right after. In the Internet I found some other variants of getting the window handle and then draw on the window but most of the crash with the same exception or just do nothing. I also tried it in a loop because I thought the app may overdraw it every frame.
So my question is has anyone an idea how I could fix this or had the same problem and an other method do this.