Search code examples
c#system.drawing

OutOfMemory exception when using Graphics.FromHwnd(...)


I tried to directly draw to the screen with the following code:

[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr ptr);

static void draw(Rectangle r, Brush b, IntPtr hwnd)
{
    using (Graphics g = Graphics.FromHwnd(hwnd))
    {
        g.FillRectangle(b, r);
    }
}
static void Main(string[] args)
{
    draw(new Rectangle(0, 0, 400, 400), Brushes.PaleGoldenrod, GetDC(IntPtr.Zero));
}

Consulting the documentation and various examples this should be valid code. Nevertheless I get a OutOfMemoryException at the following line:

using(Graphics g = Graphics.FromHwnd(hwnd))

Since I am only querying for a single handle I do not understand how this exception is raised. There is no other code in this example.


Solution

  • A DC is not an HWND. Replace Graphics.FromHwnd() with Graphics.FromHDC()