Skip to content

Instantly share code, notes, and snippets.

@codec-abc
Created December 11, 2020 23:18
Show Gist options
  • Select an option

  • Save codec-abc/2f81294f8ca7f51a854ab97e53ec5502 to your computer and use it in GitHub Desktop.

Select an option

Save codec-abc/2f81294f8ca7f51a854ab97e53ec5502 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
#include <windows.h>
#include <string>
#include <iomanip>
#include <sstream>
int width = 2;
int height = 2;
int32_t bitmap2x2[4] = { 0xffff0000, 0xff00ff00, 0xff0000ff, 0x00000000 };
void WriteBitmapFromHandle(HBITMAP source_hbitmap, UINT uFormat, int width, int height) {
// We would like to just call ::SetClipboardData on the source_hbitmap,
// but that bitmap might not be of a sort we can write to the clipboard.
// For this reason, we create a new bitmap, copy the bits over, and then
// write that to the clipboard.
HDC dc = ::GetDC(nullptr);
HDC compatible_dc = ::CreateCompatibleDC(nullptr);
HDC source_dc = ::CreateCompatibleDC(nullptr);
// This is the HBITMAP we will eventually write to the clipboard
HBITMAP hbitmap = ::CreateCompatibleBitmap(dc, width, height);
if (!hbitmap) {
// Failed to create the bitmap
::DeleteDC(compatible_dc);
::DeleteDC(source_dc);
::ReleaseDC(nullptr, dc);
return;
}
HBITMAP old_hbitmap = (HBITMAP)SelectObject(compatible_dc, hbitmap);
HBITMAP old_source = (HBITMAP)SelectObject(source_dc, source_hbitmap);
// Now we need to blend it into an HBITMAP we can place on the clipboard
BLENDFUNCTION bf = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
::GdiAlphaBlend(compatible_dc,
0,
0,
width,
height,
source_dc,
0,
0,
width,
height,
bf);
// Clean up all the handles we just opened
::SelectObject(compatible_dc, old_hbitmap);
::SelectObject(source_dc, old_source);
::DeleteObject(old_hbitmap);
::DeleteObject(old_source);
::DeleteDC(compatible_dc);
::DeleteDC(source_dc);
::ReleaseDC(nullptr, dc);
EmptyClipboard();
HANDLE data = SetClipboardData(uFormat, hbitmap);
if (data) {
std::cout << "data put on the clipboard" << std::endl;
}
::DeleteObject(source_hbitmap);
}
int main()
{
if (OpenClipboard(NULL))
{
HDC hdc = CreateCompatibleDC(NULL);
if (!hdc) {
return -1;
}
BITMAPINFO info;
info.bmiHeader.biSize = sizeof(BITMAPV5HEADER);
info.bmiHeader.biWidth = width;
info.bmiHeader.biHeight = -height;
info.bmiHeader.biPlanes = 1;
info.bmiHeader.biBitCount = 32;
info.bmiHeader.biCompression = BI_RGB;
info.bmiHeader.biSizeImage = 4 * width * height;
info.bmiHeader.biClrUsed = 0;
info.bmiHeader.biClrImportant = 0;
void* bits = NULL;
HBITMAP dib = ::CreateDIBSection(hdc, &info, DIB_RGB_COLORS, &bits, NULL, 0);
if (!dib) {
return -2;
}
memcpy(bits, &bitmap2x2[0], 4 * sizeof(int32_t));
WriteBitmapFromHandle(dib, CF_BITMAP, width, height);
if (!CloseClipboard()) {
return -3;
}
::DeleteObject(dib);
}
return 0;
}
@codec-abc
Copy link
Copy Markdown
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment