Capture screen shot with mouse cursor

3.7k views Asked by At

I have used the following code to get screen shot on Windows.

 hdcMem = CreateCompatibleDC (hdc) ;
 int cx = GetDeviceCaps (hdc, HORZRES);
 int cy = GetDeviceCaps (hdc, VERTRES);
 HBITMAP hBitmap(NULL);
 hBitmap = CreateCompatibleBitmap (hdc, cx, cy) ;
 SelectObject (hdcMem, hBitmap) ;
 BitBlt(hdcMem, 0, 0, cx, cy, hdc, 0, 0, SRCCOPY);

However, the mouse cursor doesn't show up.

How could I get the cursor? or Is there a library can do that?

Thanks in advance.

1

There are 1 answers

0
Adrian McCarthy On

After your BitBlt and before you select the bitmap back out of hdcMem, you can do this:

CURSORINFO cursor = { sizeof(cursor) };
::GetCursorInfo(&cursor);
if (cursor.flags == CURSOR_SHOWING) {
    RECT rcWnd;
    ::GetWindowRect(hwnd, &rcWnd);
    ICONINFOEXW info = { sizeof(info) };
    ::GetIconInfoExW(cursor.hCursor, &info);
    const int x = cursor.ptScreenPos.x - rcWnd.left - rc.left - info.xHotspot;
    const int y = cursor.ptScreenPos.y - rcWnd.top  - rc.top  - info.yHotspot;
    BITMAP bmpCursor = {0};
    ::GetObject(info.hbmColor, sizeof(bmpCursor), &bmpCursor);
    ::DrawIconEx(hdcMem, x, y, cursor.hCursor, bmpCursor.bmWidth, bmpCursor.bmHeight,
                 0, NULL, DI_NORMAL);
}

The code above figures out if the cursor is showing, using the global cursor state since you're probably taking a screenshot of a window (or windows) in another process. It then gets the target window coordinates for adjusting from screen. It gets specific info about the cursor, including its hotspot. It computes the drawing position of the icon. Finally, it gets the actual size of the cursor icon so that it can draw it without any stretching.

The only limitations to this approach that I know of are:

  • You don't get cursor shadows if you have them enabled.
  • If it's an animated cursor, this just shows the first frame. As far as I know, there's no way to determine the current frame.