Search code examples
winapiclipboardsandbox

how does Windows implement clipboard format conversion?


i am implementing clipboard for my application sandbox system on Windows. I have to simulate clipboard behaviors by myself. Now all work fine except for format conversion part, i can do it for CF_TEXT/UNICODETEXT/OEMTEXT, but there are other formats that i am not familiar with like DIB. Is there any sample codes illustrating how Windows does this?


Solution

  • The difference between CF_DIB and other clipboard formats is that it contains memory objects of BITMAPINFO structure and bitmap bits.

    The msdn document has provided a very detailed example:

    HINSTANCE hinst; 
    UINT uFormat = (UINT)(-1); 
    BOOL fAuto = TRUE; 
     
    LRESULT APIENTRY MainWndProc(hwnd, uMsg, wParam, lParam) 
    HWND hwnd; 
    UINT uMsg; 
    WPARAM wParam; 
    LPARAM lParam; 
    { 
        static HWND hwndNextViewer; 
     
        HDC hdc; 
        HDC hdcMem; 
        PAINTSTRUCT ps; 
        LPPAINTSTRUCT lpps; 
        RECT rc; 
        LPRECT lprc; 
        HGLOBAL hglb; 
        LPSTR lpstr; 
        HBITMAP hbm; 
        HENHMETAFILE hemf; 
        HWND hwndOwner; 
     
        switch (uMsg) 
        { 
            case WM_PAINT: 
                hdc = BeginPaint(hwnd, &ps); 
     
                // Branch depending on the clipboard format. 
     
                switch (uFormat) 
                { 
                    case CF_OWNERDISPLAY: 
                        ...
     
                    case CF_BITMAP: 
                        hdcMem = CreateCompatibleDC(hdc); 
                        if (hdcMem != NULL) 
                        { 
                            if (OpenClipboard(hwnd)) 
                            { 
                                hbm = (HBITMAP) 
                                    GetClipboardData(uFormat); 
                                SelectObject(hdcMem, hbm); 
                                GetClientRect(hwnd, &rc); 
     
                                BitBlt(hdc, 0, 0, rc.right, rc.bottom, 
                                    hdcMem, 0, 0, SRCCOPY); 
                                CloseClipboard(); 
                            } 
                            DeleteDC(hdcMem); 
                        } 
                        break; 
    ...
    

    If you need to save the obtained bitmap object as a file, then you must strictly follow the BITMAPINFOHEADER structure to assign values.

    MSDN code sample: Storing an Image