VC获取窗口图片(截图)

6 篇文章 0 订阅
//借鉴网上的文章:

HBITMAP CopyDCToBitmap(HDC hDC, LPRECT lpRect)
 {
  if(!hDC || !lpRect || IsRectEmpty(lpRect))
   return NULL;
  
  HDC hMemDC;  
  HBITMAP hBitmap, hOldBitmap;  
  int nX, nY, nX2, nY2;  
  int nWidth, nHeight; 
  
  nX = lpRect->left;
  nY = lpRect->top;
  nX2 = lpRect->right;
  nY2 = lpRect->bottom;
  nWidth = nX2 - nX;
  nHeight = nY2 - nY;
  
  hMemDC = CreateCompatibleDC(hDC);
  
  hBitmap = CreateCompatibleBitmap(hDC, nWidth, nHeight);
  
  hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);
  
  StretchBlt(hMemDC, 0, 0, nWidth, nHeight, hDC, nX, nY, nWidth, nHeight, SRCCOPY);
  
  hBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap); 
  
  DeleteDC(hMemDC);
  DeleteObject(hOldBitmap);
  
  
  return hBitmap;
 }

VC 中,在控制台窗口中添加图片要使用 GDI 库来进行绘制。下面是一个简单的例子: 1. 在项目中添加你要显示的图片。 2. 在控制台窗口中添加以下代码: ``` #include <Windows.h> #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <wingdi.h> int main() { // 打开并读取图片文件 FILE* fp = fopen("your_image.bmp", "rb"); if (fp == NULL) { printf("Error: Failed to open image file.\n"); return 1; } fseek(fp, 0, SEEK_END); int file_size = ftell(fp); fseek(fp, 0, SEEK_SET); unsigned char* data = (unsigned char*)malloc(file_size); fread(data, 1, file_size, fp); fclose(fp); // 获取控制台窗口句柄 HWND hwnd = GetConsoleWindow(); HDC hdc = GetDC(hwnd); // 获取图片宽度和高度 BITMAPINFOHEADER* header = (BITMAPINFOHEADER*)(data + 14); int width = header->biWidth; int height = header->biHeight; // 创建 DIBSection,用于存储图片数据 BITMAPINFO bmi = { 0 }; bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = -height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 24; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = 0; void* bits; HBITMAP bitmap = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, &bits, NULL, 0); // 将图片解析到 DIBSection 中 unsigned char* src = data + header->biSize + 14; unsigned char* dest = (unsigned char*)bits; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int offset = y * width * 3 + x * 3; dest[offset + 0] = src[offset + 2]; dest[offset + 1] = src[offset + 1]; dest[offset + 2] = src[offset + 0]; } } // 绘制图片 HDC memdc = CreateCompatibleDC(hdc); HBITMAP oldbitmap = (HBITMAP)SelectObject(memdc, bitmap); BitBlt(hdc, 0, 0, width, height, memdc, 0, 0, SRCCOPY); SelectObject(memdc, oldbitmap); DeleteObject(bitmap); DeleteDC(memdc); // 释放内存 free(data); // 等待按键 while (_kbhit() == 0) {} return 0; } ``` 这段代码首先使用 fopen() 函数打开并读取图片文件,然后使用 GetConsoleWindow() 函数获取控制台窗口句柄,使用 GetDC() 函数获取控制台窗口的 DC(设备上下文)。接着,通过解析图片数据并创建 DIBSection 存储图像数据,最后使用 BitBlt() 函数将图片绘制到控制台窗口上。最后,使用 _kbhit() 函数等待按键,当有按键按下程序结束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值