天天看點

VC++-螢幕截圖

  • 版本

VS2012

  • 執行個體說明

執行個體完成一個螢幕截圖軟體

可以将螢幕的内容保持到位圖檔案内

  • 關鍵技術

螢幕截圖需要先建立一個螢幕的裝置上下文,然後根據螢幕的裝置上下文建立一個記憶體位圖,最後将記憶體位圖資料寫入到檔案就實作了螢幕截圖操作,螢幕截圖程式需要運作在系統托盤中,并且通過RegisterHotKey函數注冊一個快截鍵,通過快截鍵進行截圖操作。

  • 設計過程

(1)建立基于對話框的應用程式。

(2)在對話框中添加按鈕控件

(3)方法SaveScreen是接收到觸發後的儲存螢幕圖像的實作。

  • 源代碼
void CFirstMFCDialog::OnBnClickedButtonscreenshot()
{
    // TODO: 在此添加控件通知處理程式代碼

    CDC screendc;
    screendc.CreateDC("DISPLAY", NULL, NULL, NULL);
    CBitmap bmp;
    int width = GetSystemMetrics(SM_CXSCREEN);
    int height = GetSystemMetrics(SM_CYSCREEN);
    bmp.CreateCompatibleBitmap(&screendc, width, height);
    CDC memdc;
    memdc.CreateCompatibleDC(&screendc);
    CBitmap* old = memdc.SelectObject(&bmp);
    memdc.BitBlt(0,0,width,height,&screendc,0,0,SRCCOPY);
    memdc.SelectObject(old);
    BITMAP bm;
    bmp.GetBitmap(&bm);
    DWORD size = bm.bmWidthBytes*bm.bmHeight;
    LPSTR data = (LPSTR)GlobalAlloc(GPTR,size);
    BITMAPINFOHEADER bih;
    bih.biBitCount = bm.bmBitsPixel;
    bih.biClrImportant = 0;
    bih.biClrUsed = 0;
    bih.biCompression = 0;
    bih.biHeight = bm.bmHeight;
    bih.biWidth = bm.bmWidth;
    bih.biPlanes = 1;
    bih.biSize = sizeof(BITMAPINFOHEADER);
    bih.biSizeImage = size;
    bih.biXPelsPerMeter = 0;
    bih.biYPelsPerMeter = 0;
    GetDIBits(screendc, bmp, 0, bih.biHeight, data, (BITMAPINFO*)&bih,DIB_RGB_COLORS);
    CFile file;
    BITMAPFILEHEADER hdr;
    hdr.bfType = ((WORD)('M'<<8)|'B');
    hdr.bfSize = 54 + size;
    hdr.bfReserved1 = 0;
    hdr.bfReserved2 = 0;
    hdr.bfOffBits = 54;
    if (file.Open("D:\\2\\test.bmp",CFile::modeCreate|CFile::modeWrite))
    {
        file.Write(&hdr, sizeof(BITMAPFILEHEADER));
        file.Write(&bih, sizeof(BITMAPINFOHEADER));
        file.Write(data, size);
        file.Close();
    }

    GlobalFree(data);
    Invalidate();
}      
  • 示範
VC++-螢幕截圖