Public Class FormSnapShot

    Private m_Bitmap As Bitmap
    Private m_SavedFg As Boolean = False

    Private Sub SaveImage()
        If Not m_Bitmap Is Nothing Then
            If DialogResult.OK = SaveFileDialog1.ShowDialog() Then
                m_Bitmap.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Bmp)
                m_SavedFg = True
            End If
        End If
    End Sub


    Public Function bUpdateSnapShot(ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal pbyteImg() As Byte, ByVal nBufferSize As Integer, ByVal pixelFormat As Imaging.PixelFormat) As Boolean

        Dim bitmap As Bitmap = New Bitmap(nWidth, nHeight, pixelFormat)

        Select Case pixelFormat
            Case Imaging.PixelFormat.Format8bppIndexed
                'Palette
                Dim colorPalette As System.Drawing.Imaging.ColorPalette = bitmap.Palette
                For pixelValue As Integer = 0 To 255
                    colorPalette.Entries(pixelValue) = Color.FromArgb(pixelValue, pixelValue, pixelValue)
                Next
                bitmap.Palette = colorPalette
        End Select

        'Copy
        Dim bitmapData As Imaging.BitmapData = bitmap.LockBits(New Rectangle(0, 0, nWidth, nHeight), Imaging.ImageLockMode.WriteOnly, pixelFormat)
        Runtime.InteropServices.Marshal.Copy(pbyteImg, 0, bitmapData.Scan0(), nBufferSize)
        bitmap.UnlockBits(bitmapData)

        If Not m_Bitmap Is Nothing Then
            PictureBox1.Image = Nothing
            m_Bitmap.Dispose()
        End If
        m_Bitmap = bitmap
        Me.WindowState = FormWindowState.Normal
        Me.ClientSize = New Size(nWidth, nHeight)
        Me.MaximumSize = Me.Size
        PictureBox1.Location = New Point(0, 0)
        PictureBox1.Image = m_Bitmap
        m_SavedFg = False


        Return True
    End Function


    Private Sub FormSnapShot_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If e.KeyCode = Keys.Apps Then
            ContextMenuStrip1.Show(Me, Me.PointToClient(MousePosition))
        End If
    End Sub

    Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
        SaveImage()
    End Sub

    Private Sub FormSnapShot_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If Not m_SavedFg Then
            If DialogResult.Yes = Windows.Forms.MessageBox.Show("Do You Want To Save The Image?", "Save Image", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) Then
                SaveImage()
            End If
        End If
        If Not m_Bitmap Is Nothing Then
            PictureBox1.Image = Nothing
            m_Bitmap.Dispose()
            m_Bitmap = Nothing
        End If
    End Sub
End Class