Skip to content
This repository was archived by the owner on Jul 26, 2023. It is now read-only.
This repository was archived by the owner on Jul 26, 2023. It is now read-only.

[Question] Issue with IntPtr versus Safehandles in Gdi32.BitBlt #593

Closed

Description

@josdemmers

I was wondering if I was missing some overload functions or I'm implementing this wrong.
Will first post the relevant code:

public Bitmap GetScreenCapture(IntPtr handle)
{
      Bitmap bitmap;

      PInvoke.RECT region;
      PInvoke.User32.GetWindowRect(handle, out region);
      
      var desktopWindowHandle = PInvoke.User32.GetDesktopWindow();
      var windowDCHandle = PInvoke.User32.GetWindowDC(desktopWindowHandle);
      var memoryDCHandle = PInvoke.Gdi32.CreateCompatibleDC(windowDCHandle);
      var bitmapHandle = PInvoke.Gdi32.CreateCompatibleBitmap(windowDCHandle, region.right - region.left, region.bottom - region.top);
      var bitmapOldHandle = PInvoke.Gdi32.SelectObject(memoryDCHandle, bitmapHandle);

      bool success = PInvoke.Gdi32.BitBlt(memoryDCHandle, 0, 0, region.right - region.left, region.bottom - region.top, windowDCHandle, region.left, region.top, SRCCOPY | CAPTUREBLT);

      try
      {
        bitmap = Image.FromHbitmap(bitmapHandle);
      }
      finally
      {
        PInvoke.Gdi32.SelectObject(memoryDCHandle, bitmapOldHandle);
        PInvoke.Gdi32.DeleteObject(bitmapHandle);
        PInvoke.Gdi32.DeleteDC(memoryDCHandle);
        PInvoke.User32.ReleaseDC(desktopWindowHandle, windowDCHandle);
      }

      return bitmap;
}

The issue is the function BitBlt wants IntPtr as input while the functions GetWindowDC and CreateCompatibleDC both return a SafeDCHandle.
Is there an overload for GetWindowDC and CreateCompatibleDC that return an IntPtr instead? Or can I make BitBlt to somehow accept the SafeDCHandles?

Before using this package I would use the code below. But this package sound really great. Safes a lot of time defining all the windows library functions you want to use.

[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);

Activity

  1. added a commit that references this issue on Jan 24, 2022
    45a9e65
  2. AArnott commented on Jan 24, 2022

    @AArnott
    Collaborator

    I suspect BitBlt should take SafeDCHandle as well. I'll send a PR to do this.
    In the meantime you can always get the IntPtr from a SafeHandle using DangerousGetHandle(). Check the documentation on SafeHandle to learn how to use it safely for this.

  3. added a commit that references this issue on Jan 25, 2022
    7a51f66
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions