4

How can I capture screen and save it as am image in C?
OS: windows (XP & Seven)

Thanks

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
Ariyan
  • 14,760
  • 31
  • 112
  • 175
  • That's a bit vague and depends hugely on the underlying OS. In any case, you'd have to go through the API that comes with your OS, fetch raw pixel data, and save it as an image - for that last part, you probably want to use an existing library so you won't be reinventing the wheel. – tdammers Jul 30 '10 at 10:58
  • Please consider adding information to this question. Operating system? Graphics environment? Available libraries? – sepp2k Jul 30 '10 at 10:59
  • 1
    You are probably looking to use some combination of `BitBlt`, `GetDC` and `GetDesktopWindow`. – dreamlax Jul 30 '10 at 11:24
  • 2
    possible duplicate of [What is the best way to take screenshots of a Window with C++ in Windows?](http://stackoverflow.com/questions/531684/what-is-the-best-way-to-take-screenshots-of-a-window-with-c-in-windows) – kennytm Jul 30 '10 at 11:37

2 Answers2

5

Have you tried google? This forum entry has an example, complete with C source code using the Win32 API.

EDIT: Found a duplicate in the meantime: How can I take a screenshot and save it as JPEG on Windows?

Community
  • 1
  • 1
Greg S
  • 12,333
  • 2
  • 41
  • 48
5

in case you don't want to bother to click on link

#include <windows.h>

bool SaveBMPFile(char *filename, HBITMAP bitmap, HDC bitmapDC, int width, int height);

bool ScreenCapture(int x, int y, int width, int height, char *filename){
  // get a DC compat. w/ the screen
  HDC hDc = CreateCompatibleDC(0);

  // make a bmp in memory to store the capture in
  HBITMAP hBmp = CreateCompatibleBitmap(GetDC(0), width, height);

  // join em up
  SelectObject(hDc, hBmp);

  // copy from the screen to my bitmap
  BitBlt(hDc, 0, 0, width, height, GetDC(0), x, y, SRCCOPY);

  // save my bitmap
  bool ret = SaveBMPFile(filename, hBmp, hDc, width, height);

  // free the bitmap memory
  DeleteObject(hBmp);

  return ret;
}

main(){
  ScreenCapture(500, 200, 300, 300, "testScreenCap.bmp");
  system("pause");
}
rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Mihir Mehta
  • 13,743
  • 3
  • 64
  • 88
  • Hi, This doesn't work for me too! I thought we don't have "bool" datatype in C (?) . it rises this error : "expected '=', ',', ';', 'asm' or '__attribute__' before 'SaveBMPFile'" & the same error for "ScreenCapture" function – Ariyan Aug 02 '10 at 14:20
  • Try the following: typedef char bool; #define true 1 #define false 0 – phyrrus9 Sep 24 '13 at 15:52
  • 1
    OK, for followers I took the liberty of putting together a compilable file (including the absent SaveBMPFile method) here: https://gist.github.com/rdp/9821698 (@4r1y4n you need to compile using g++) – rogerdpack Mar 27 '14 at 23:44
  • 1
    This question was not tagged "c++". – carefulnow1 Dec 11 '16 at 18:16