Working C# code for the Windows clipboard?
How do I convert the following C++ code (for taking a Bitmap from the Clipboard and copy it onto a form), into a WPF C# code that also uses APIs (not inbuilt Clipboard helpers from the .NET Framework) to copy it int开发者_开发知识库o a BitmapSource (or Bitmap for that matter)?
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);
}
My implementation in WPF C# code is as follows. Probably awfully wrong. The thing is that I am getting a black image out of it.
IntPtr hdc = CreateCompatibleDC(IntPtr.Zero);
IntPtr hdcMem = CreateCompatibleBitmap(hdc, 64, 64);
if (hdcMem != null)
{
if (OpenClipboard(MainWindow.Handle))
{
IntPtr hbm = GetClipboardData((uint)clipboardFormat);
SelectObject(hdcMem, hbm);
BitBlt(hdc, 0, 0, 64, 64, hdcMem, 0, 0, TernaryRasterOperations.SRCCOPY);
CloseClipboard();
}
DeleteDC(hdcMem);
}
I wrote a custom implementation to workaround the bug in Clipboard.GetImage
, you can find it here.
Something like this
IntPtr hDstdc = CreateCompatibleDC(IntPtr.Zero);
IntPtr hDstBm = CreateCompatibleBitmap(hDstdc, 64, 64);
SelectObject(hDstdc, hDstBm);
IntPtr hSrcdc = CreateCompatibleDC(IntPtr.Zero);
...
IntPtr hSrcbm = GetClipboardData((uint)clipboardFormat);
SelectObject(hSrcDc, hSrcbm);
BitBlt(hDstdc, 0, 0, 64, 64, hSrcdc, 0, 0, TernaryRasterOperations.SRCCOPY).
You have to create two display contexts, then you create the destination bitmap and get the source bitmap from the clipboard, then you select each bitmap into a display context, and then you call BitBlt.
But really it's a long time since I've done this stuff, I'm not making any promises.
精彩评论