Darren Ng
Darren Ng

Reputation: 373

CreateCompatibleBitmap returns Overlapped I/O Operation Is In Progress

It's a fairly standard screen capture function using BitBlt that's found in the net:

Main Function:

while(true)
{
    printscreen = GetDesktopImage(X, Y, secMonitorSize.Width, secMonitorSize.Height);
    Thread.Sleep(1000);
}

Capture Desktop function:

public Bitmap GetDesktopImage(int X, int Y, int width, int height)
{
    IntPtr hDC = WIN32_API.GetDC(WIN32_API.GetDesktopWindow());
    IntPtr hMemDC = WIN32_API.CreateCompatibleDC(hDC);
    IntPtr m_HBitmap = WIN32_API.CreateCompatibleBitmap(hDC, width, height);

    if (m_HBitmap != IntPtr.Zero)
    {
        IntPtr hOld = (IntPtr)WIN32_API.SelectObject(hMemDC, m_HBitmap);
        WIN32_API.BitBlt(hMemDC, 0, 0, width, height, hDC, X, Y, WIN32_API.SRCCOPY | WIN32_API.CAPTURE_BLT);

        WIN32_API.SelectObject(hMemDC, hOld);
        WIN32_API.DeleteDC(hMemDC);
        WIN32_API.ReleaseDC(WIN32_API.GetDesktopWindow(), hDC);

        Bitmap printscreen = System.Drawing.Image.FromHbitmap(m_HBitmap);
        WIN32_API.DeleteObject(m_HBitmap);

        return printscreen;
    }

    return null;
}

The problem is that the code runs fine for roughly 20 mins, then CreateCompatibleBitmap will keep returning 0. Using setlasterror=true on CreateCompatibleBitmap, it displays the error code 997 (Overlapped I/O Operation Is In Progress).

There's only symantec running in the background. Anyone have any idea how do I start troubleshooting?

Upvotes: 0

Views: 1533

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595981

GDI functions do not use GetLastError(), so using setlasterror=true will report errors from earlier API calls.

Try this:

public Bitmap GetDesktopImage(int X, int Y, int width, int height)
{
    Bitmap printscreen = null;

    IntPtr hWnd = WIN32_API.GetDesktopWindow();
    IntPtr hDC = WIN32_API.GetDC(hWnd);
    if (hDC != IntPtr.Zero)
    { 
        IntPtr hMemDC = WIN32_API.CreateCompatibleDC(hDC);
        if (hMemDC != IntPtr.Zero)
        {
            IntPtr m_HBitmap = WIN32_API.CreateCompatibleBitmap(hDC, width, height);
            if (m_HBitmap != IntPtr.Zero)
            {
                IntPtr hOld = (IntPtr)WIN32_API.SelectObject(hMemDC, m_HBitmap);
                WIN32_API.BitBlt(hMemDC, 0, 0, width, height, hDC, X, Y, WIN32_API.SRCCOPY | WIN32_API.CAPTURE_BLT);
                WIN32_API.SelectObject(hMemDC, hOld);

                printscreen = System.Drawing.Image.FromHbitmap(m_HBitmap);
                WIN32_API.DeleteObject(m_HBitmap);
            }

            WIN32_API.DeleteDC(hMemDC);
        }

        WIN32_API.ReleaseDC(hWnd, hDC);
    }

    return printscreen;
}

Upvotes: 3

Related Questions