VC进行屏幕截取编程的方法
下面用vc来逐步介绍在windows95下的实现过程.首先我们要确定屏幕截取的区域,用lprect结构来定义.可以截取一个窗口,或整个屏幕.以下代码把选定的屏幕区域拷贝到位图中.
hbitmap copyscreentobitmap(lprect lprect)
//lprect 代表选定区域
{
hdc hscrdc, hmemdc;
// 屏幕和内存设备描述表
hbitmap hbitmap, holdbitmap;
// 位图句柄
int nx, ny, nx2, ny2;
// 选定区域坐标
int nwidth, nheight;
// 位图宽度和高度
int xscrn, yscrn;
// 屏幕分辨率
// 确保选定区域不为空矩形
if (isrectempty(lprect))
return null;
//为屏幕创建设备描述表
hscrdc = createdc("display", null, null, null);
//为屏幕设备描述表创建兼容的内存设备描述表
hmemdc = createcompatibledc(hscrdc);
// 获得选定区域坐标
nx = lprect- >left;
ny = lprect- >top;
nx2 = lprect- >right;
ny2 = lprect- >bottom;
// 获得屏幕分辨率
xscrn = getdevicecaps(hscrdc, horzres);
yscrn = getdevicecaps(hscrdc, vertres);
//确保选定区域是可见的
if (nx 〈0)
nx = 0;
if (ny 〈 0)
ny = 0;
if (nx2 > xscrn)
nx2 = xscrn;
if (ny2 > yscrn)
ny2 = yscrn;
nwidth = nx2 - nx;
nheight = ny2 - ny;
// 创建一个与屏幕设备描述表兼容的位图
hbitmap = createcompatiblebitmap
(hscrdc, nwidth, nheight);
// 把新位图选到内存设备描述表中
holdbitmap = selectobject(hmemdc, hbitmap);
// 把屏幕设备描述表拷贝到内存设备描述表中
bitblt(hmemdc, 0, 0, nwidth, nheight,
hscrdc, nx, ny, srccopy);
//得到屏幕位图的句柄
hbitmap = selectobject(hmemdc, holdbitmap);
//清除
deletedc(hscrdc);
deletedc(hmemdc);
// 返回位图句柄
return hbitmap;
}
得到屏幕位图句柄以后,我们
可以把屏幕内容粘贴到剪贴板上.
if (openclipboard(hwnd))
//hwnd为程序窗口句柄
{
//清空剪贴板
emptyclipboard();
//把屏幕内容粘贴到剪贴板上,
hbitmap 为刚才的屏幕位图句柄
setclipboarddata(cf_bitmap, hbitmap);
//关闭剪贴板
closeclipboard();
}
我们也可以把屏幕内容以位图格式存到磁盘文件上.
int savebitmaptofile(hbitmap hbitmap ,
lpstr lpfilename) //hbitmap 为刚才的屏幕位图句柄
{ //lpfilename 为位图文件名
hdc hdc;
//设备描述表
int ibits;
//当前显示分辨率下每个像素所占字节数
word wbitcount