简单的截屏

来源:互联网 发布:电脑淘宝微淘入口 编辑:程序博客网 时间:2024/05/20 01:37
#include <windows.h>#include <atlimage.h>voidSaveBitmap(char *szFilename,HBITMAP hBitmap){  HDChdc=NULL;  FILE*fp=NULL;  LPVOIDpBuf=NULL;  BITMAPINFObmpInfo;  BITMAPFILEHEADERbmpFileHeader;  do{    hdc=GetDC(NULL);    ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));    bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);    GetDIBits(hdc,hBitmap,0,0,NULL,&bmpInfo,DIB_RGB_COLORS);    if(bmpInfo.bmiHeader.biSizeImage<=0)      bmpInfo.bmiHeader.biSizeImage=bmpInfo.bmiHeader.biWidth*abs(bmpInfo.bmiHeader.biHeight)*(bmpInfo.bmiHeader.biBitCount+7)/8;    if((pBuf=malloc(bmpInfo.bmiHeader.biSizeImage))==NULL)    {      MessageBox(NULL,_T("Unable to Allocate Bitmap Memory"),_T("Error"),MB_OK|MB_ICONERROR);      break;    }    bmpInfo.bmiHeader.biCompression=BI_RGB;    GetDIBits(hdc,hBitmap,0,bmpInfo.bmiHeader.biHeight,pBuf,&bmpInfo,DIB_RGB_COLORS);    if((fp=fopen(szFilename,"wb"))==NULL)    {      MessageBox(NULL,_T("Unable to Create Bitmap File"),_T("Error"),MB_OK|MB_ICONERROR);      break;    }    bmpFileHeader.bfReserved1=0;    bmpFileHeader.bfReserved2=0;    bmpFileHeader.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+bmpInfo.bmiHeader.biSizeImage;    bmpFileHeader.bfType='MB';    bmpFileHeader.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);    fwrite(&bmpFileHeader,sizeof(BITMAPFILEHEADER),1,fp);    fwrite(&bmpInfo.bmiHeader,sizeof(BITMAPINFOHEADER),1,fp);    fwrite(pBuf,bmpInfo.bmiHeader.biSizeImage,1,fp);  }while(false);  if(hdc)    ReleaseDC(NULL,hdc);  if(pBuf)    free(pBuf);  if(fp)    fclose(fp);}void getAppScreenShot(const char *appName, char *saveBmpName){   HWND hAppWnd = ::FindWindow(0, appName);  HDC hAppDC = ::GetDC(hAppWnd);  RECT rc;  ::GetClientRect(hAppWnd, &rc);  intnWidth = rc.right - rc.left;  intnHeight = rc.bottom - rc.top;  HDChBmpFileDC=CreateCompatibleDC(hAppDC);  HBITMAPhBmpFileBitmap=CreateCompatibleBitmap(hAppDC,nWidth,nHeight);  HBITMAP hOldBitmap = (HBITMAP) SelectObject(hBmpFileDC,hBmpFileBitmap);  BitBlt(hBmpFileDC,0,0,nWidth,nHeight,hAppDC,0,0,SRCCOPY|CAPTUREBLT);  SelectObject(hBmpFileDC,hOldBitmap);  SaveBitmap(saveBmpName,hBmpFileBitmap);  DeleteDC(hBmpFileDC);  DeleteObject(hBmpFileBitmap);}int main(){  getAppScreenShot("计算器", "1.bmp");  return 0;}

原创粉丝点击