最简单的屏幕拷贝程序(象素拷贝)

类别:VC语言 点击:0 评论:0 推荐:

////////////////////////////////////////////////

//小弟工作之余写了一个程序,

//注意,该程序非常占用CPU时间,它的唯好处就是简单,可以一个象素一个象素的操作

//您还可以根据需要改变象素的值达到特殊的效果。

//本程序在WIN2000下测试通过,可以获取256色以上个种分辨率的屏幕

//自定义RGB象素Structure
typedef struct tagRBBREQUIRED
{
 BYTE rgbBlue;
 BYTE rgbGREEN;
 BYTE rgbRed;
} RGBREQUIRED, *PRGBREQUIRED;


int APIENTRY WinMain ( HINSTANCE hInstance,
                       HINSTance hPrevInstance,
                       LPSTR     lpCmdLine,
                       int       nCmdShow)
{
 HDC  hdcScr;
 int  cx, cy;
        BITMAPFILEHEADER  BFH;
        BITMAPINFOHEADER  BIH;
 WORD wType;
 LONG lSize;
 LONG lPixNum;
 BYTE byte;

 PRGBREQUIRED pPixel = NULL;
 fstream      *out;


 cx = GetSystemMetrics ( SM_CXSCREEN );
 cy = GetSystemMetrics ( SM_CYSCREEN );

 lSize = sizeof ( RGBREQUIRED ) * cy * cx;
 lPixNum = cy * cx ;

 byte  = 'M';
 wType = (byte << 8);
 byte  = 'B';
 wType =  wType + byte;
 

//填写位图信息头
 BIH.biSize = sizeof (BIH);
 BIH.biHeight = cy;
 BIH.biWidth  = cx;
 BIH.biClrImportant = 0;
 BIH.biClrUsed      = 0;
 BIH.biCompresion   = BI_RGB;
 BIH.biPlaned       = 1;
 BIH.biSizeImage    = lSize + 44;
 BIH.biXPelsPerMeter = 3780;
 BIH.biYPelsPerMeter = 3780;
 BIH.biBitCount      = 24;

//填写位图文件头

 BFH.bfType = wType;
 BFH.bfSize = lSize;
 BFH.bfOffBits = sizeof ( BFH ) + sizeof ( BIH );
 BFH.bfReserved1 = 0;
 BFH.bfReserved2 = 0;

 hdcScr = GetDC ( NULL );
 if ( !hdcScr )
 {
  MessageBox ( NULL, "Can't get the screen handle", "Error", MB_OK );
  return 0;
 }

 pPixel = new RGBREQUIRED[lPixNum];

 if ( !pPixel )

{

   MessageBox ( NULL, "Can't alloc memory", "Error", MB_OK);

   return 0;

 }
 memset ( ( void * ) pPixel, 0, lSize );
 PRGBREQUIRED pTemp = pPixel;
 RGBREQUIRED  TmpPix;
 DWORD        colorRef;
 int          i, j;

 for ( i=cy-1; i>=0; i-- )
 for ( j=0   ; j<cx; j++ )
 {
  colorRef = GetPixel ( hdcScr, j, i ); //获取象素的色彩值00BBGGRR
  TmpPix.rgbBlue  = (BYTE) ( ( colorRef & 0x00ff0000 ) >> 16 );
  TmpPix.rgbGreen = (BYTE) ( ( colorRef & 0x0000ff00 ) >> 16 );
  TmpPix.rgbRed   = (BYTE)  ( colorRef & 0x000000ff ); 
  *pTemp = TmpPix;
 }

//保存文件

 out = new fstream ( "screen.bmp", ios::out|ios::binary, filebuf::sh_none );
 
 if ( !out )
 {

  delete pPixel;

  pPixel = NULL;

  pTemp  = NULL;
  MessageBox ( NULL, "Can't open file", "Error", MB_OK );
  return 0;
 }

 out->write ( ( char* )&BFH, sizeof ( BITMAPFILEHEADER ) ); //写入位图文件头
 out->write ( ( char* )&BIH, sizeof ( BITMAPINFOHEADER ) ); //写入位图信息头
 out->write ( ( char* )&pPixel, lSize );

 out->close();

 delete pPixel;
 pPixel = NULL;
 pTemp  = NULL;

 MessageBox ( NULL, "Copy screen successfully!", "Congratulations", MB_OK);
 return 0;
}

 

                      

本文地址:http://com.8s8s.com/it/it1637.htm