示例#1
0
 private static async Task OpenClipboard()
 {
     while (!Win32UnmanagedMethods.OpenClipboard(IntPtr.Zero))
     {
         await Task.Delay(100);
     }
 }
示例#2
0
    private static async Task SetBitmapAsync(System.Drawing.Bitmap systemBitmap)
    {
        //var bitmapStream = new MemoryStream();
        //systemBitmapPng.Save(bitmapStream, ImageFormat.Bmp);
        //var systemBitmap = new System.Drawing.Bitmap(bitmapStream); // .bmp version imports clearer than .png

        var hBitmap = systemBitmap.GetHbitmap();

        IntPtr screenDC = Win32UnmanagedMethods.GetDC(IntPtr.Zero);

        using var sourceDC = Gdi32UnmanagedMethods.CreateCompatibleDCScoped(screenDC);

        if (sourceDC.HDC == IntPtr.Zero)
        {
            return;
        }

        IntPtr sourceBitmapSelection = Gdi32UnmanagedMethods.SelectObject(sourceDC, hBitmap);

        if (sourceBitmapSelection == IntPtr.Zero)
        {
            return;
        }

        using var destDC = Gdi32UnmanagedMethods.CreateCompatibleDCScoped(screenDC);

        if (destDC.HDC == IntPtr.Zero)
        {
            return;
        }

        IntPtr compatibleBitmap = Gdi32UnmanagedMethods.CreateCompatibleBitmap(screenDC, systemBitmap.Width, systemBitmap.Height);

        if (compatibleBitmap == IntPtr.Zero)
        {
            return;
        }

        IntPtr destinationBitmapSelection = Gdi32UnmanagedMethods.SelectObject(destDC, compatibleBitmap);

        if (destinationBitmapSelection == IntPtr.Zero)
        {
            return;
        }

        if (!Gdi32UnmanagedMethods.BitBlt(
                destDC,
                0,
                0,
                systemBitmap.Width,
                systemBitmap.Height,
                sourceDC,
                0,
                0,
                SRCCOPY))
        {
            throw new Exception("BitBlt failed");
        }

        try
        {
            await OpenClipboard();

            Win32UnmanagedMethods.EmptyClipboard();

            IntPtr result = Win32UnmanagedMethods.SetClipboardData(Win32UnmanagedMethods.ClipboardFormat.CF_BITMAP, compatibleBitmap);

            if (result == IntPtr.Zero)
            {
                int errno = Marshal.GetLastWin32Error();
                throw new Exception("SetClipboardData failed: Error = " + errno);
            }
        }
        finally
        {
            Win32UnmanagedMethods.CloseClipboard();
        }
    }