1

I'm trying to copy parts of the screen, modify them, and then copy those parts back to the screen. This is in windows, using C++.

The general structure of my code looks like this:

HDC hdcDesktop = GetDC(NULL);
HDC hdcTemp = CreateCompatibleDC(hdcDesktop);

BitBlt(hdcTemp, 0, 0, 100, 100, hdcDesktop, 100, 100, SRCCOPY);
BitBlt(hdcDesktop, rand() % 1920, rand() % 1080, 100, 100, hdcTemp, 0, 0, SRCCOPY);

This should copy a 100x100 portion of the screen starting at (100, 100) to some random part of the screen. This doesn't work, however. What am I doing wrong?

some guy
  • 682
  • 2
  • 7
  • 16
  • 2
    You forgot CreateCompatibleBitmap + SelectObject. http://msdn.microsoft.com/en-us/library/dd183402%28v=VS.85%29.aspx – Hans Passant Apr 07 '12 at 06:16
  • Ahaaa. I was looking at that page earlier but got confused, so I re-read the top a bit more clearly. Thanks! – some guy Apr 07 '12 at 06:32

1 Answers1

2

There are a few issues with this code:

  1. As indicated by the docs, CreateCompatibleDC creates a new in-memory image that is 1x1 pixels. This is obviously not big enough for your 100x100 chunk of image. You should probably use CreateCompatibleBitmap.

  2. The coordinates passed to BitBlt are:

    • top-left cornder of destination (nXDest, nYDest)
    • width/height of copy (nWidth,nHeight)
    • top-left corner of soruce (nXSrc,nYSrc)

    in that order. You seem to be confusing nXSrc/nYSrc with nWidth/nHeight. Check your numbers.

  3. Wanton abuse of the desktop surface like this may actually (1) be disallowed and (2) produce unexpected results. Be careful what you are attempting to achieve.

Michael Slade
  • 13,802
  • 2
  • 39
  • 44
  • Thanks, this worked for me (5 years ago!) I feel like finally adding some context for this - I was trying to make an annoying program with no practical purpose except to completely goof up someone's screen. So, I would definitely call this wanton abuse, and for this project it worked out perfectly. – some guy Sep 26 '19 at 21:08