Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

使用DDA捕获桌面截图,并在Win32窗口显示

  1. User

    使用DDA捕获桌面截图,并在Win32窗口显示

  2. Assistant

    以下是使用DDA捕获桌面截图并在Win32窗口显示的步骤:

    1. 首先要包含Windows.h和dwmapi.h头文件。
    2. 声明dwmapi.dll库中的DwmGetWindowAttribute函数, 用于获取指定HWND的属性,如窗口图像和缩略图。
    3. 创建一个用于存储屏幕截图像素的位图(HBITMAP)。
    4. 使用GetDC(NULL)函数获取桌面设备上下文。
    5. 使用CreateCompatibleDC(NULL)函数创建与桌面设备上下文兼容的设备上下文。
    6. 使用CreateCompatibleBitmap函数创建一个与设备上下文兼容的位图,并将其与设备上下文关联。
    7. 使用SelectObject将位图与设备上下文关联。
    8. 使用StretchBlt函数将桌面设备上下文中的像素复制到设备上下文中。
    9. 创建一个窗口并将其内容设置为位图。
    10. 在窗口中使用UpdateWindow函数更新内容。
    11. 在消息循环中使用PeekMessage和TranslateMessage以响应用户输入。
    12. 在退出窗口前使用DeleteDC函数和DeleteObject函数释放内存。

    下面是完整的代码:

    #include <Windows.h> #include <dwmapi.h>

    #pragma comment(lib, "dwmapi.lib")

    LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

    HBITMAP captureScreen() { HDC hScreenDC = GetDC(NULL); HDC hDC = CreateCompatibleDC(hScreenDC); HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); HGDIOBJ oldBitmap = SelectObject(hDC, hBitmap); StretchBlt(hDC, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), hScreenDC, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SRCCOPY); SelectObject(hDC, oldBitmap); DeleteDC(hDC); ReleaseDC(NULL, hScreenDC); return hBitmap; }

    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wcex; memset(&wcex, 0, sizeof(wcex)); wcex.cbSize = sizeof(WNDCLASSEX); wcex.lpfnWndProc = WndProc; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.lpszClassName = L"ScreenCapture"; RegisterClassEx(&wcex);

    HWND hWnd = CreateWindow(L"ScreenCapture", L"Screen Capture", WS_OVERLAPPEDWINDOW,
                              CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
    
    if (!hWnd)
        return FALSE;
    
    HBITMAP hBitmap = captureScreen();
    HWND hStatic = CreateWindow(L"STATIC", NULL, WS_CHILD | WS_VISIBLE | SS_BITMAP,
                                0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
                                hWnd, NULL, hInstance, NULL);
    SendMessage(hStatic, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);
    UpdateWindow(hStatic);
    
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    
    ReleaseDC(hWnd, GetDC(hWnd));
    DeleteObject(hBitmap);
    return (int)msg.wParam;
    

    }

    LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }