Search code examples
vb.netscale

VB Scale form for screen capture


I am trying to do a screen capture using the code below

    Dim area As Rectangle = FormPrintArea.Bounds
    Dim areaWidth As Integer = CInt(area.Width * ScaleFactor)
    Dim areaHeight As Integer = CInt(area.Height * ScaleFactor)
    Dim capture As Bitmap = New Bitmap(areaWidth, areaHeight, PixelFormat.Format32bppArgb)
    Dim graph As Graphics = Graphics.FromImage(capture)
    Dim ScaledSize As New Size With {
        .Height = areaHeight,
        .Width = areaWidth
    }
    graph.CopyFromScreen(area.X, area.Y, 0, 0, ScaledSize, CopyPixelOperation.SourceCopy)
    PictureBox1.Image = capture

`` The problem is I can't find ScaleFactor, Everything works perfect as long as "Change the size of text, apps and the other items: 100%" in Windows 10 Display Settings but if it is set differently like 125% (recommended), I lose about 20% of the image. It looks like there is a ScaleFactor in the LanguageFont class but I can't seem to access it from VB (or C#).

The application has a VB Form (FormPrintArea) that the user uses to define the print area. If I set ScaleFactor to 1.25 on systems set to 125% (recommended), then everything works. Is there any way to get the value from Windows through an API? ScaleFactor 1

ScaleFactor 1.25


Solution

  • I needed to declare my App DPIaware as @Hans Passant said, the easiest way is to add the lines below to the Partial Class startup form (Form1).

    <DllImport("User32.dll")> Private Shared Sub SetProcessDPIAware() End Sub

    Then change the New Sub at the end of the startup form to call SetProcessDPIAware

    Public Sub New() SetProcessDPIAware() InitializeComponent() End Sub

    Once you do that you can get the ScaleFactor in Form1.Load as follows DPIScalingX = Me.CreateGraphics().DpiX / 96 DPIScalingY = Me.CreateGraphics().DpiY / 96