CreateCompatibleBitmap returns NULL



I'm capturing the screen using the following code , but the problem i have
that after 43 calls of the functions the NULL reference object is returned ,

SIZE size;

//Here we get the handle to the desktop device context.
IntPtr hDC =
//Here we make a compatible device context in memory for screen device
IntPtr hMemDC = PlatformInvokeGDI32.CreateCompatibleDC(hDC);
//We pass SM_CXSCREEN constant to GetSystemMetrics to get the X coordinates
of screen. =
//We pass SM_CYSCREEN constant to GetSystemMetrics to get the Y coordinates
of screen. =

//We create a compatible bitmap of screen size and using screen device
m_HBitmap = PlatformInvokeGDI32.CreateCompatibleBitmap(hDC,,;

//Here m_HBitmap return be NULL(Zero) after 43 calls of the function...WHY?

//As m_HBitmap is IntPtr we can not check it against null. For this purspose
IntPtr.Zero is used.
if (m_HBitmap!=IntPtr.Zero)
//Here we select the compatible bitmap in memeory device context and keeps
the refrence to Old bitmap.
IntPtr hOld = (IntPtr) PlatformInvokeGDI32.SelectObject(hMemDC, m_HBitmap);
//We copy the Bitmap to the memory device context.
PlatformInvokeGDI32.BitBlt(hMemDC, 0, 0,,, hDC, 0, 0,
//We select the old bitmap back to the memory device context.
PlatformInvokeGDI32.SelectObject(hMemDC, hOld);
//We delete the memory device context.
//We release the screen device context.
PlatformInvokeUSER32.ReleaseDC(PlatformInvokeUSER32.GetDesktopWindow(), hDC);
//Image is created by Image bitmap handle and returned.
return System.Drawing.Image.FromHbitmap(m_HBitmap);
//If m_HBitmap is null retunrn null.
return null;


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question