0
votes

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.

1
what does that hwnd suppose to point to ? - Tigran
This is returned from GetDC which, according to its documentation, behaves as following: hwnd: A handle to the window whose DC is to be retrieved. If this value is NULL, GetDC retrieves the DC for the entire screen. - Lukas Häfliger
Device context is not a HWND, is not a handler to a window. It is a device context, for rendering. Change that method as suggested in posted answer. - Tigran

1 Answers

4
votes

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