' CAPTURA DE PANTALLA
' VISUAL BASIC .NET
' MILIUCO

Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging

Public Class Form1
    Inherits System.Windows.Forms.Form


#Region " Código generado por el Diseñador de Windows Forms "

    Public Sub New()
        MyBase.New()

        'El Diseñador de Windows Forms requiere esta llamada.
        InitializeComponent()

        'Agregar cualquier inicialización después de la llamada a InitializeComponent()

    End Sub

    'Form reemplaza a Dispose para limpiar la lista de componentes.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Requerido por el Diseñador de Windows Forms
    Private components As System.ComponentModel.IContainer

    'NOTA: el Diseñador de Windows Forms requiere el siguiente procedimiento
    'Puede modificarse utilizando el Diseñador de Windows Forms. 
    'No lo modifique con el editor de código.
    Friend WithEvents btGrab As System.Windows.Forms.Button
    Friend WithEvents btSalir As System.Windows.Forms.Button
    Friend WithEvents btGrab2 As System.Windows.Forms.Button
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Timer1 As System.Windows.Forms.Timer
    Friend WithEvents btHelp As System.Windows.Forms.Button
    Friend WithEvents imgEmi As System.Windows.Forms.PictureBox
    Friend WithEvents Panel1 As System.Windows.Forms.Panel
    Friend WithEvents imgPantalla As System.Windows.Forms.PictureBox
    Friend WithEvents Timer2 As System.Windows.Forms.Timer
    Friend WithEvents Label3 As System.Windows.Forms.Label
    Friend WithEvents ToolTip1 As System.Windows.Forms.ToolTip
    Friend WithEvents dlgGuardar As System.Windows.Forms.OpenFileDialog
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1))
        Me.btGrab = New System.Windows.Forms.Button
        Me.btSalir = New System.Windows.Forms.Button
        Me.imgPantalla = New System.Windows.Forms.PictureBox
        Me.btGrab2 = New System.Windows.Forms.Button
        Me.Label1 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.Timer1 = New System.Windows.Forms.Timer(Me.components)
        Me.btHelp = New System.Windows.Forms.Button
        Me.imgEmi = New System.Windows.Forms.PictureBox
        Me.Panel1 = New System.Windows.Forms.Panel
        Me.Timer2 = New System.Windows.Forms.Timer(Me.components)
        Me.Label3 = New System.Windows.Forms.Label
        Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
        Me.dlgGuardar = New System.Windows.Forms.OpenFileDialog
        Me.Panel1.SuspendLayout()
        Me.SuspendLayout()
        '
        'btGrab
        '
        Me.btGrab.BackColor = System.Drawing.SystemColors.Control
        Me.btGrab.Cursor = System.Windows.Forms.Cursors.Default
        Me.btGrab.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btGrab.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btGrab.ForeColor = System.Drawing.Color.Black
        Me.btGrab.Location = New System.Drawing.Point(344, 88)
        Me.btGrab.Name = "btGrab"
        Me.btGrab.Size = New System.Drawing.Size(160, 32)
        Me.btGrab.TabIndex = 0
        Me.btGrab.TabStop = False
        Me.btGrab.Text = "Captura de pantalla"
        '
        'btSalir
        '
        Me.btSalir.BackColor = System.Drawing.SystemColors.Control
        Me.btSalir.Cursor = System.Windows.Forms.Cursors.Default
        Me.btSalir.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btSalir.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btSalir.Location = New System.Drawing.Point(96, 224)
        Me.btSalir.Name = "btSalir"
        Me.btSalir.Size = New System.Drawing.Size(64, 32)
        Me.btSalir.TabIndex = 1
        Me.btSalir.TabStop = False
        Me.btSalir.Text = "Salir"
        '
        'imgPantalla
        '
        Me.imgPantalla.BackColor = System.Drawing.Color.Gray
        Me.imgPantalla.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.imgPantalla.Location = New System.Drawing.Point(8, 8)
        Me.imgPantalla.Name = "imgPantalla"
        Me.imgPantalla.Size = New System.Drawing.Size(320, 248)
        Me.imgPantalla.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
        Me.imgPantalla.TabIndex = 2
        Me.imgPantalla.TabStop = False
        '
        'btGrab2
        '
        Me.btGrab2.BackColor = System.Drawing.SystemColors.Control
        Me.btGrab2.Cursor = System.Windows.Forms.Cursors.Default
        Me.btGrab2.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btGrab2.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btGrab2.ForeColor = System.Drawing.Color.Black
        Me.btGrab2.Location = New System.Drawing.Point(344, 152)
        Me.btGrab2.Name = "btGrab2"
        Me.btGrab2.Size = New System.Drawing.Size(160, 32)
        Me.btGrab2.TabIndex = 1
        Me.btGrab2.TabStop = False
        Me.btGrab2.Text = "Captura de ventana"
        '
        'Label1
        '
        Me.Label1.AutoSize = True
        Me.Label1.BackColor = System.Drawing.SystemColors.Control
        Me.Label1.CausesValidation = False
        Me.Label1.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.ForeColor = System.Drawing.Color.Black
        Me.Label1.Location = New System.Drawing.Point(360, 128)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(134, 16)
        Me.Label1.TabIndex = 2
        Me.Label1.Text = "Destino C:\EmiScreen.jpg"
        Me.ToolTip1.SetToolTip(Me.Label1, "Archivo destino de la captura")
        '
        'Label2
        '
        Me.Label2.AutoSize = True
        Me.Label2.BackColor = System.Drawing.SystemColors.Control
        Me.Label2.CausesValidation = False
        Me.Label2.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label2.ForeColor = System.Drawing.Color.Black
        Me.Label2.Location = New System.Drawing.Point(368, 192)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(118, 16)
        Me.Label2.TabIndex = 3
        Me.Label2.Text = "Destino C:\EmiWin.jpg"
        Me.ToolTip1.SetToolTip(Me.Label2, "Archivo destino de la captura")
        '
        'Timer1
        '
        Me.Timer1.Interval = 2500
        '
        'btHelp
        '
        Me.btHelp.BackColor = System.Drawing.SystemColors.Control
        Me.btHelp.Cursor = System.Windows.Forms.Cursors.Default
        Me.btHelp.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.btHelp.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btHelp.Location = New System.Drawing.Point(16, 224)
        Me.btHelp.Name = "btHelp"
        Me.btHelp.Size = New System.Drawing.Size(64, 32)
        Me.btHelp.TabIndex = 0
        Me.btHelp.TabStop = False
        Me.btHelp.Text = "Ayuda"
        '
        'imgEmi
        '
        Me.imgEmi.BackColor = System.Drawing.Color.Transparent
        Me.imgEmi.Image = CType(resources.GetObject("imgEmi.Image"), System.Drawing.Image)
        Me.imgEmi.Location = New System.Drawing.Point(24, 24)
        Me.imgEmi.Name = "imgEmi"
        Me.imgEmi.Size = New System.Drawing.Size(120, 32)
        Me.imgEmi.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
        Me.imgEmi.TabIndex = 6
        Me.imgEmi.TabStop = False
        '
        'Panel1
        '
        Me.Panel1.BackColor = System.Drawing.SystemColors.Control
        Me.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
        Me.Panel1.Controls.Add(Me.imgEmi)
        Me.Panel1.Controls.Add(Me.btHelp)
        Me.Panel1.Controls.Add(Me.btSalir)
        Me.Panel1.Location = New System.Drawing.Point(336, 8)
        Me.Panel1.Name = "Panel1"
        Me.Panel1.Size = New System.Drawing.Size(176, 272)
        Me.Panel1.TabIndex = 4
        '
        'Timer2
        '
        Me.Timer2.Interval = 1500
        '
        'Label3
        '
        Me.Label3.AutoSize = True
        Me.Label3.BackColor = System.Drawing.SystemColors.Control
        Me.Label3.CausesValidation = False
        Me.Label3.FlatStyle = System.Windows.Forms.FlatStyle.System
        Me.Label3.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label3.ForeColor = System.Drawing.Color.Black
        Me.Label3.Location = New System.Drawing.Point(64, 264)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(196, 17)
        Me.Label3.TabIndex = 5
        Me.Label3.Text = "Miniatura de la imagen capturada"
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(520, 292)
        Me.Controls.Add(Me.Label3)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.btGrab2)
        Me.Controls.Add(Me.imgPantalla)
        Me.Controls.Add(Me.btGrab)
        Me.Controls.Add(Me.Panel1)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.Name = "Form1"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.Manual
        Me.Text = "  Captura de pantalla"
        Me.Panel1.ResumeLayout(False)
        Me.ResumeLayout(False)

    End Sub

#End Region

    ' Variable para ser utilizada en el método mnGuardar_Click
    Dim nombreImgGuardar As String = ""

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Posiciones x,y del formulario
        Me.DesktopLocation = New Point(120, 100)
    End Sub

    ' Botón que activa el temporizador1 (intervalo: 2,5 segundos)
    Private Sub btGrab2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btGrab2.Click
        Timer1.Enabled = True
        Timer1.Start()
    End Sub

    ' Botón que activa el temporizador 2 (intervalo: 2,5 segundos)
    Private Sub btGrab_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btGrab.Click
        'minimizar el formulario para que no aparezca en la captura
        Me.WindowState = FormWindowState.Minimized
        Timer2.Enabled = True
        Timer2.Start()
    End Sub

    'Temporizador 1 -> llama a la función GetWindowCapture (que captura
    'al portapapeles la ventana activa), guarda la captura como BMP
    'en C:\EmiWin.bmp y la muestra en el PictureBox
    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        'guardar la captura como JPG
        GetWindowCapture().Save("c:\EmiWin.jpg", ImageFormat.Jpeg)
        'poner la captura en el control imgPantalla
        imgPantalla.Image = GetWindowCapture()
        'formulario al primer plano con el foco
        Me.Activate()
        'detener el temporizador
        Timer1.Stop()
        Timer1.Enabled = False
    End Sub

    ' Temporizador 2 -> llama a la función GetScreenCapture (que captura
    'al portapapeles la pantalla), guarda la captura como JPG
    'en C:\EmiScreen.bmp y la muestra en el PictureBox
    Private Sub Timer2_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        'guardar la captura como BMP
        GetScreenCapture().Save("c:\EmiScreen.jpg", ImageFormat.Jpeg)
        'poner la captura en el control imgPantalla
        imgPantalla.Image = GetScreenCapture()
        'detener el temporizador
        Timer2.Stop()
        Timer2.Enabled = False
        'restaurar el formulario a su tamaño normal desde minimizado
        Me.WindowState = FormWindowState.Normal
    End Sub

    ' Función que captura la pantalla mediante el envío de la pulsación de la
    ' tecla "IMPR PANT". La función devuelve un objeto Image y lo coloca en el portapapeles.
    Public Function GetScreenCapture() As Image
        '
        'La clase SendKeys proporciona métodos para enviar pulsaciones 
        'de tecla a la aplicación activa. No se puede crear una instancia de esta clase.
        'Para enviar una pulsación de tecla y continuar inmediatamente con el flujo del
        'programa, utilice Send. Para esperar a que terminen los procesos iniciados por
        'la pulsación de tecla, utilice SendWait.
        'Cada tecla está representada por uno o más caracteres. Para especificar un 
        'único carácter del teclado, utilice dicho carácter. Por ejemplo, para representar
        'la letra A, pase la cadena "A" al método. Si se desea representar más de un 
        'carácter, agregue cada carácter adicional al que lo precede. Para representar las
        'letras A, B y C, especifique el parámetro como "ABC".
        'El signo más (+), el signo de intercalación (^), el signo de porcentaje (%), la tilde (~)
        'y los paréntesis () tienen significados especiales para SendKeys. Para especificar
        'uno de estos caracteres, inclúyalo entre llaves ({}). Por ejemplo, para especificar el
        'signo más, utilice "{+}".
        'Para especificar caracteres que no se muestran al presionar una tecla, como ENTRAR
        'o TAB, y teclas que representan acciones en lugar de caracteres, utilice códigos como:
        'RETROCESO - usar {BACKSPACE}, {BS} o {BKSP}
        'ESC - usar {ESC}
        'IMPR PANT - usar {PRTSC}
        'Para especificar teclas con cualquier combinación de las teclas MAYÚS, CTRL y ALT,
        'escriba delante del código de la tecla: % para ALT, ^ para CTRL y + para MAYÜS
        'Para especificar una repetición de teclas, utilice el formato {tecla número}. Hay que
        'separar la tecla y el número con un espacio.
        'Como ejemplo de todo ello, para enviar 1 pulsación de ALT + IMPR PANT (captura
        'la ventana activa) usaremos %{PRTSC} y para enviar 2 pulsaciones de IMPR PANT
        '(captura la pantalla entera) usaremos {PRTSC 2}
        '
        'variable que guarda la pulsación de la tecla
        Dim objTecla As SendKeys
        '2 pulsaciones de IMPR PANT para capturar la pantalla entera
        objTecla.SendWait("{PRTSC 2}")
        'variable de tipo IDataObject que contiene el portapapeles
        'GetDataObject() es un método de IDataObject
        Dim objClipboard As IDataObject = Clipboard.GetDataObject()
        'devolver el portapapeles como mapa de bits
        Return objClipboard.GetData(DataFormats.Bitmap)
    End Function

    ' Función que captura la ventana mediante el envío de la pulsación de la
    ' tecla "IMPR PANT". La función devuelve un objeto Image y lo coloca en el portapapeles
    Public Function GetWindowCapture() As Image
        'variable que guarda la pulsación de la tecla
        Dim objTecla As SendKeys
        '1 pulsación de ALT + IMPR PANT para capturar la ventana activa
        objTecla.SendWait("%{PRTSC}")
        'variable de tipo IDataObject que contiene el portapapeles
        'GetDataObject() es un método de IDataObject
        Dim objClipboard As IDataObject = Clipboard.GetDataObject() ' portapapeles
        'devolver el portapapeles como mapa de bits
        Return objClipboard.GetData(DataFormats.Bitmap)
    End Function

    'Salir de la aplicación
    Private Sub btSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btSalir.Click
        Close()
    End Sub

    'Cuadro con información sobre el programa
    Private Sub btHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btHelp.Click
        MessageBox.Show("Este programa realiza capturas de la pantalla o de la ventana activa" & vbCrLf & _
        "usando el método SendKeystrokes, al que se le pasa un parámetro String" & vbCrLf & _
        "y envía a la ventana activa  la pulsación de la tecla referida en esa cadena." & vbCrLf & _
        "La pantalla se captura cuando han transcurrido 1,5 segundos." & vbCrLf & _
        "La ventana se captura cuando han transcurrido 2,5 segundos." & vbCrLf & _
        "Las capturas se copian al portapapeles y también se guardan en el disco duro como JPEG", _
        "Información de Miliuco", MessageBoxButtons.OK)
    End Sub

End Class