1、進入截圖狀态
prtscring = true;//開始截圖示志為true
afxgetmainwnd()->showwindow(sw_showmaximized);//主視窗最大化
setwindowlong(getsafehwnd(), gwl_exstyle, ::getwindowlongptr(getsafehwnd(), gwl_exstyle) | ws_ex_layered);
this->setlayeredwindowattributes(0, (255 * 1) / 100, lwa_alpha);//設定透明度為1%
cbutton *begin_btn = (cbutton*)getdlgitem(idc_btn_begin);//開始截圖按鈕
cbutton *exit_btn = (cbutton*)getdlgitem(idc_btn_exit);//退出程式按鈕
begin_btn->showwindow(false);//截圖按鈕不可見
exit_btn->showwindow(false);//退出程式按鈕不可見
setclasslong(this->getsafehwnd(), gcl_hcursor, (long)loadcursor(null, idc_cross));//設定截圖時的光标為十字
2、滑鼠左鍵按下消息函數
if (prtscring == true)//如果是在截圖狀态下滑鼠左鍵按下
{
begin_point = point;//存儲滑鼠左鍵按下的坐标
cdialogex::onlbuttondown(nflags, point);
}
3、滑鼠左鍵彈起消息函數
if (prtscring == true)//如果是在截圖狀态下滑鼠左鍵彈起
prtscring = false;//開始截圖示志為false
prtscred = true;//截圖結束标志為true
end_point = point;//得到截圖結束時的坐标
int weith, heith;
weith = (end_point.x > begin_point.x ? end_point.x - begin_point.x : begin_point.x - end_point.x);//截圖的寬度
heith = (end_point.y > begin_point.y ? end_point.y - begin_point.y : begin_point.y - end_point.y);//截圖的長度
/*如果截圖的面積太小,會影響視覺感,人為增大*/
if (weith < 50)
weith = 50;
if (heith < 100)
heith = 100;
setwindowpos(null, 0, 0, weith, heith, swp_showwindow);//把主視窗大小設定成使用者截圖的圖檔大小
//setwindowlong(m_hwnd, gwl_style, getwindowlong(m_hwnd, gwl_style) & ~ws_caption); //去标題欄
//setwindowlong(m_hwnd, gwl_exstyle, getwindowlong(m_hwnd, gwl_exstyle) & ~(ws_ex_windowedge | ws_ex_dlgmodalframe)); //去邊框
cdc *pdesktopdc = getdesktopwindow()->getdc();//擷取全螢幕dc
crect rect;//擷取主視窗矩形對象
this->getclientrect(&rect);
cdc *pdc = this->getdc();//擷取主視窗dc
/*用stretchblt函數将源矩形的位圖複制到目标矩形*/
pdc->stretchblt(0, 0, rect.width(), rect.height(), pdesktopdc, begin_point.x>end_point.x ? end_point.x : begin_point.x, begin_point.y > end_point.y ? end_point.y : begin_point.y, weith, heith, srccopy);//核心函數,将全螢幕的截圖區域複制在主視窗上面顯示
::setwindowlong(getsafehwnd(), gwl_exstyle, ::getwindowlongptr(getsafehwnd(), gwl_exstyle) | ws_ex_layered);
this->setlayeredwindowattributes(0, (255 * 100) / 100, lwa_alpha);//恢複正常透明度
cbutton *save_btn = (cbutton *)getdlgitem(2000);//儲存截圖按鈕
save_btn->showwindow(true);//這個儲存按鈕是我在初始化函數中生成的,本來是不可見的,當截圖完成後,這個按鈕就可見
4、儲存按鈕函數
cbutton *save_btn = (cbutton*)getdlgitem(2000);//在點選了儲存按鈕之後,這個按鈕不可見
save_btn->showwindow(false);
cdc *pdc = getwindowdc();//擷取主視窗裝置上下文
cdc memdc;//記憶體裝置上下文
memdc.createcompatibledc(pdc);
crect rt;//擷取主視窗的矩形
getwindowrect(&rt);
cbitmap bmp;
bmp.createcompatiblebitmap(pdc, rt.width(), rt.height());
cbitmap *pbmpprev = (cbitmap*)memdc.selectobject(&bmp);
memdc.bitblt(0, 0, rt.width(), rt.height(), pdc, 0, 0, srccopy);
cimage image;
image.attach((hbitmap)bmp.m_hobject);
image.save(l"c:\\1.bmp");
長風破浪會有時,直挂雲帆濟滄海!