Windows screencopy .net api not working as expected due to scaling issue

36 Views Asked by At

Using the following I am able to take a screenshot of the current window into a bitmap object

Function ScreenShotWindow() As Bitmap
    Dim bmpScreenshot As Bitmap = New Bitmap(Me.Width, Me.Height)

    Using g = Graphics.FromImage(bmpScreenshot)
        g.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, Me.Size)
        Return bmpScreenshot
    End Using
End Function

(I've rewritten the above sample to simplify it, so there may be a syntax error, or two)

This technique works fine using my PC, or other PCs, when run from the console. However, when I execute the same code via RDP, the image is 'chopped', by which I mean the bitmap is smaller than the window and is missing some of the bottom and right of the window. This occurs consistently when connected via RDP.

So, it would seem I should be taking a scaling factor into account and going about the task in a slightly different way. All the above values refer to the number of pixels, which I would have thought apply the same regardless, but it seems not.

I've tried searching for scaling related documentation but no luck. I'm probably searching for the wrong thing.

Anyone know what I should be doing or what I should be looking at in the docs?

1

There are 1 best solutions below

3
Mustafa Özçetin On

Use the Control.DrawToBitmap method.

I have tested the following code with both local and remote desktop machines and it works fine. Use it in your Form class.

Sub SaveWindowScreenshot(outputPath As String)
    Using bmp = New Bitmap(Width, Height)
        DrawToBitmap(bmp, New Rectangle(0, 0, bmp.Width, bmp.Height))
        bmp.Save(outputPath)
    End Using
End Sub