jingwood / d2dlib

A .NET library for hardware-accelerated, high performance, immediate mode rendering via Direct2D.
MIT License
234 stars 40 forks source link

Import HBitmap directly? #57

Closed BergChristian closed 3 years ago

BergChristian commented 3 years ago

Hi!

I am capture the screen and trying to present the captured image in a D2DImage. Everything works fine, but the question is if it can be more efficient.

Right now I am getting a hBitmap from the Cope screen function, which I convert into a GDI which I send to D2D image which converts it back to an hbitmap?

Do you think there could be an option to feed the hbitmap directly?

success = BitBlt(memoryDc, 0, 0, region.Width, region.Height, desktopDc, region.Left, region.Top, RasterOperations.SRCCOPY Or RasterOperations.CAPTUREBLT)

    D2Dimage.Dispose()
    D2Dimage = Nothing
    D2Dimage = device.CreateBitmapFromGDIBitmap(image.FromHbitmap(bitmap))

Best Christian

Dim desktophWnd As IntPtr Dim desktopDc As IntPtr Dim memoryDc As IntPtr Dim bitmap As IntPtr Dim oldBitmap As IntPtr Dim success As Boolean 'Dim result As Bitmap desktophWnd = GetDesktopWindow() desktopDc = GetWindowDC(desktophWnd) memoryDc = CreateCompatibleDC(desktopDc) bitmap = CreateCompatibleBitmap(desktopDc, region.Width, region.Height) oldBitmap = SelectObject(memoryDc, bitmap)

    success = BitBlt(memoryDc, 0, 0, region.Width, region.Height, desktopDc, region.Left, region.Top, RasterOperations.SRCCOPY Or RasterOperations.CAPTUREBLT)

    D2Dimage.Dispose()
    D2Dimage = Nothing
    D2Dimage = device.CreateBitmapFromGDIBitmap(image.FromHbitmap(bitmap))

    SelectObject(memoryDc, oldBitmap)
    DeleteObject(bitmap)
    DeleteDC(memoryDc)
    ReleaseDC(desktophWnd, desktopDc)
jingwood commented 3 years ago

I have added a new API method CreateBitmapFromHBitmap, you can try this method from the latest source code.

D2Dimage = device.CreateBitmapFromHBitmap(hbitmap)

2b4f395063af1bfcf283d059e6e545f1723adbf2

By the way, if you capture the entire screen, you may consider to use this method, which doesn't need to use hbitmap. I am not sure if it brings better performance. https://stackoverflow.com/questions/5049122/capture-the-screen-shot-using-net

BergChristian commented 3 years ago

Thanks! Way much faster and more importantly less memory usage. An awesome library just got better!

Christian

BergChristian commented 3 years ago

And.. Thanks for the link. I wanted to capture a region of the screen. Trying to capture a window but having issues with application which are hardware rendered so right now the best effort is to capture a part of a screen but I really would like to capture a window and the content of it rather than the screen.

jingwood commented 3 years ago

Glad to hear that works.