Search code examples
vb.netformsimage

VB.NET 2019 - How to Create and Save a bitmap or jpeg file image of the current form?


I have an application that uses a single form that allow users to manipulate settings used to calculate various parameters. All that works until I came to want to;

  1. Want to save an image of that calculation (i.e. an image of the form) or
  2. Print it.

I have found various solutions but most use C# code not VB.NET, those that have used VB.Net seem to create classes that are confusing me.

Basically I can add a button to the form, that I'd like to hide once pressed by using (btnXYZ.Visible=false), then proceed to generate an image file that I can save.

Please can somebody help? Thank you.


Solution

  • Try this:

    Private Function GetSnapShot() As Bitmap
        Using image As Image = New Bitmap(Me.Width - 10, Me.Height - 10)
            Using graphics As Graphics = graphics.FromImage(image)
                graphics.CopyFromScreen(New Point(Me.Left + 5, Me.Top + 5), Point.Empty, New Size(Me.Width - 10, Me.Height - 10))
            End Using
            Return New Bitmap(SetBorder(image, Color.Black, 1))
        End Using
    End Function
    
    Private Function SetBorder(ByVal srcImg As Image, ByVal color As Color, ByVal width As Integer) As Image
        Dim dstImg As Image = srcImg.Clone()
        Dim g As Graphics = Graphics.FromImage(dstImg)
        Dim pBorder As Pen = New Pen(color, width)
    
        pBorder.Alignment = Drawing2D.PenAlignment.Center
        g.DrawRectangle(pBorder, 0, 0, dstImg.Width - 1, dstImg.Height - 1)
        pBorder.Dispose()
        g.Save()
        g.Dispose()
    
        Return dstImg
    End Function
    

    And this is how to use the code:

    GetSnapShot().Save("File Path goes here where you want to save the image")