elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Arreglado, de nuevo, el registro del warzone (wargame) de EHN


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [APORTE] Screen-Region Selector (para capturadores de pantalla)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [APORTE] Screen-Region Selector (para capturadores de pantalla)  (Leído 1,611 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
[APORTE] Screen-Region Selector (para capturadores de pantalla)
« en: 28 Junio 2014, 08:06 am »

Hola

Desarrollé este Snippet para que dibuja una forma cuadrada/rectangular sobre la pantalla para seleccionar un área de la imagen en movimiento, y devuelve los datos de la estructura del rectángulo seleccionado para, posteriormente, poder capturar esa región de la imagen.

Hay 2 formas (que yo sepa al menos) de llevar esto a cabo, una es "congelando" la imagen, y la otra es en tiempo real, yo opté por la segunda opción, a pesar de ser mucho más complicada es lo que se adaptaba a mis necesidades.

Espero que puedan sacar algo de provecho en este código.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 06-03-2014
  4. ' ***********************************************************************
  5. ' <copyright file="RegionSelector.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Public Class Form1
  13.  
  14. '    Dim SelectedRegion As Rectangle = Rectangle.Empty
  15. '    Dim RegionSelectorIsWorking As Boolean = False
  16.  
  17. '    Private Sub Button_Click() Handles Button1.Click
  18. '        GetScreenRegion()
  19. '    End Sub
  20.  
  21. '    Public Sub GetScreenRegion()
  22.  
  23. '        Dim Callback As RegionSelector.RegionSelectedDelegate
  24.  
  25. '        Dim Selector As New RegionSelector(BorderColor:=Color.YellowGreen,
  26. '                                           BorderSize:=3,
  27. '                                           backgroundcolor:=Color.YellowGreen,
  28. '                                           BackgroundOpacity:=0.06R)
  29.  
  30. '        Select Case RegionSelectorIsWorking
  31.  
  32. '            Case True ' Only one selection at once!
  33. '                Exit Sub
  34.  
  35. '            Case Else
  36. '                RegionSelectorIsWorking = True
  37. '                Callback = New RegionSelector.RegionSelectedDelegate(AddressOf SelectionFinished)
  38.  
  39. '                With Selector
  40. '                    .Callback = Callback
  41. '                    .Show()
  42. '                End With
  43.  
  44. '        End Select
  45.  
  46. '        ' Don't do any stuff here... do it in Rectangle Drawn...
  47.  
  48. '    End Sub
  49.  
  50. '    Private Sub SelectionFinished(ByVal Region As Rectangle)
  51.  
  52. '        RegionSelectorIsWorking = False ' Allow draw again.
  53. '        Me.SelectedRegion = Region
  54.  
  55. '        Dim sb As New System.Text.StringBuilder
  56. '        With sb
  57. '            .AppendLine("Selected Area")
  58. '            .AppendLine()
  59. '            .AppendLine("· Size")
  60. '            .AppendLine(String.Format("Width: {0}", CStr(SelectedRegion.Width)))
  61. '            .AppendLine(String.Format("Height: {0}", CStr(SelectedRegion.Height)))
  62. '            .AppendLine()
  63. '            .AppendLine("· Coordinates")
  64. '            .AppendLine(String.Format("Top: {0}", CStr(SelectedRegion.Top)))
  65. '            .AppendLine(String.Format("Left: {0}", CStr(SelectedRegion.Left)))
  66. '            .AppendLine(String.Format("Right: {0}", CStr(SelectedRegion.Right)))
  67. '            .AppendLine(String.Format("Bottom: {0}", CStr(SelectedRegion.Bottom)))
  68. '            .AppendLine()
  69. '        End With
  70.  
  71. '        MessageBox.Show(sb.ToString)
  72.  
  73. '    End Sub
  74.  
  75. 'End Class
  76.  
  77. #End Region
  78.  
  79. ''' <summary>
  80. ''' Selects a region on the Screen.
  81. ''' </summary>
  82. Public NotInheritable Class RegionSelector : Inherits Form
  83.  
  84. #Region " Delegates "
  85.  
  86.    ''' <summary>
  87.    ''' Delegate RegionSelectedDelegate.
  88.    ''' </summary>
  89.    ''' <param name="Region">The region.</param>
  90.    Public Delegate Sub RegionSelectedDelegate(ByVal Region As Rectangle)
  91.  
  92. #End Region
  93.  
  94. #Region " Properties "
  95.  
  96.    ''' <summary>
  97.    ''' Callback to be invoked when drawing is done...
  98.    ''' </summary>
  99.    ''' <value>Delegate of Region Selected</value>
  100.    Public Property Callback As RegionSelectedDelegate = Nothing
  101.  
  102.    ''' <summary>
  103.    ''' Gets or sets the border size of the region selector.
  104.    ''' </summary>
  105.    ''' <value>The size of the border.</value>
  106.    Public Property BorderSize As Integer = 2
  107.  
  108.    ''' <summary>
  109.    ''' Gets or sets the border color of the region selector.
  110.    ''' </summary>
  111.    ''' <value>The color of the border.</value>
  112.    Public Property BorderColor As Color = Color.Red
  113.  
  114.    ''' <summary>
  115.    ''' Gets or sets the background color of the region selector.
  116.    ''' </summary>
  117.    ''' <value>The color of the border.</value>
  118.    Public Property BackgroundColor As Color = Color.RoyalBlue
  119.  
  120.    ''' <summary>
  121.    ''' Gets or sets the background opacity of the region selector.
  122.    ''' </summary>
  123.    ''' <value>The color of the border.</value>
  124.    Public Property BackgroundOpacity As Double = 0.08R
  125.  
  126.    ''' <summary>
  127.    ''' Gets the rectangle that contains the selected region.
  128.    ''' </summary>
  129.    Public ReadOnly Property SelectedRegion As Rectangle
  130.        Get
  131.            Return Me.DrawRect
  132.        End Get
  133.    End Property
  134.  
  135. #End Region
  136.  
  137. #Region " Objects "
  138.  
  139.    ''' <summary>
  140.    ''' Indicates the initial location when the mouse left button is clicked.
  141.    ''' </summary>
  142.    Private InitialLocation As Point = Point.Empty
  143.  
  144.    ''' <summary>
  145.    ''' The rectangle where to draw the region.
  146.    ''' </summary>
  147.    Public DrawRect As Rectangle = Rectangle.Empty
  148.  
  149.    ''' <summary>
  150.    ''' The Graphics object to draw on the screen.
  151.    ''' </summary>
  152.    Private ScreenGraphic As Graphics = Graphics.FromHwnd(IntPtr.Zero)
  153.  
  154.    ''' <summary>
  155.    ''' Indicates the Rectangle Size.
  156.    ''' </summary>
  157.    Dim DrawSize As Size
  158.  
  159.    ''' <summary>
  160.    ''' Indicates the draw form.
  161.    ''' </summary>
  162.    Dim DrawForm As Form
  163.  
  164.    ''' <summary>
  165.    ''' Indicates whether the RegionSelector is busy drawing the rectangle.
  166.    ''' </summary>
  167.    Public IsDrawing As Boolean = False
  168.  
  169. #End Region
  170.  
  171. #Region " Constructors "
  172.  
  173.    ''' <summary>
  174.    ''' Initializes a new instance of the <see cref="RegionSelector"/> class.
  175.    ''' </summary>
  176.    Public Sub New()
  177.    End Sub
  178.  
  179.    ''' <summary>
  180.    ''' Initializes a new instance of the <see cref="RegionSelector" /> class.
  181.    ''' </summary>
  182.    ''' <param name="BorderColor">Indicates the border color of the region selector.</param>
  183.    ''' <param name="BorderSize">Indicates the border size of the region selector.</param>
  184.    ''' <param name="BackgroundColor">Indicates the background color of the region selector.</param>
  185.    ''' <param name="BackgroundOpacity">Indicates the background opacity size of the region selector.</param>
  186.    Public Sub New(Optional ByVal BorderColor As Color = Nothing,
  187.                   Optional ByVal BorderSize As Integer = 2,
  188.                   Optional ByVal BackgroundColor As Color = Nothing,
  189.                   Optional ByVal BackgroundOpacity As Double = 0.1R)
  190.  
  191.        If BorderColor = Nothing _
  192.        OrElse BorderColor = Color.Transparent Then
  193.            BorderColor = Color.Red
  194.        End If
  195.  
  196.        If BackgroundColor = Nothing _
  197.        OrElse BackgroundColor = Color.Transparent Then
  198.            BackgroundColor = Color.Black
  199.        End If
  200.  
  201.        Me.BorderSize = BorderSize
  202.        Me.BorderColor = BorderColor
  203.        Me.BackgroundOpacity = BackgroundOpacity
  204.        Me.BackgroundColor = BackgroundColor
  205.  
  206.    End Sub
  207.  
  208. #End Region
  209.  
  210. #Region " Event Handlers "
  211.  
  212.    ''' <summary>
  213.    ''' Handles the Load event of the RegionSelector.
  214.    ''' </summary>
  215.    ''' <param name="sender">The source of the event.</param>
  216.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  217.    Private Sub RegionSelector_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
  218.  
  219.        Me.SuspendLayout()
  220.  
  221.        Me.AutoScaleMode = AutoScaleMode.None
  222.        Me.BackColor = Me.BackgroundColor
  223.        Me.BackgroundImageLayout = ImageLayout.None
  224.        Me.CausesValidation = False
  225.        Me.ClientSize = New Size(0, 0)
  226.        Me.ControlBox = False
  227.        Me.Cursor = Cursors.Cross
  228.        Me.DoubleBuffered = True
  229.        Me.FormBorderStyle = FormBorderStyle.None
  230.        Me.MaximizeBox = False
  231.        Me.MinimizeBox = False
  232.        Me.Name = "RegionSelector"
  233.        Me.Opacity = Me.BackgroundOpacity
  234.        Me.ShowIcon = False
  235.        Me.ShowInTaskbar = False
  236.        Me.SizeGripStyle = SizeGripStyle.Hide
  237.        Me.StartPosition = FormStartPosition.CenterScreen
  238.        Me.TopMost = False
  239.        Me.WindowState = FormWindowState.Maximized
  240.  
  241.        Me.ResumeLayout(False)
  242.  
  243.        Me.DrawForm = New DrawingRegionClass(Me)
  244.        With DrawForm
  245.            .AutoScaleMode = AutoScaleMode.None
  246.            .BackColor = Color.Tomato
  247.            .BackgroundImageLayout = ImageLayout.None
  248.            .ControlBox = False
  249.            .FormBorderStyle = FormBorderStyle.None
  250.            .MaximizeBox = False
  251.            .MinimizeBox = False
  252.            .ShowIcon = False
  253.            .ShowInTaskbar = False
  254.            .SizeGripStyle = SizeGripStyle.Hide
  255.            .StartPosition = FormStartPosition.CenterScreen
  256.            .TopLevel = True
  257.            .TopMost = True
  258.            .TransparencyKey = Color.Tomato
  259.            .WindowState = FormWindowState.Maximized
  260.        End With
  261.  
  262.        Me.AddOwnedForm(Me.DrawForm)
  263.        Me.DrawForm.Show()
  264.  
  265.    End Sub
  266.  
  267.    ''' <summary>
  268.    ''' Raises the <see cref="E:System.Windows.Forms.Control.MouseDown" /> event.
  269.    ''' </summary>
  270.    ''' <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs" /> that contains the event data.</param>
  271.    Protected Overrides Sub OnMouseDown(ByVal e As MouseEventArgs)
  272.  
  273.        If e.Button = MouseButtons.Left Then
  274.            Me.InitialLocation = e.Location
  275.            Me.IsDrawing = True
  276.        End If
  277.  
  278.    End Sub
  279.  
  280.    ''' <summary>
  281.    ''' Raises the <see cref="E:System.Windows.Forms.Control.MouseUp" /> event.
  282.    ''' </summary>
  283.    ''' <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs" /> that contains the event data.</param>
  284.    Protected Overrides Sub OnMouseUp(ByVal e As MouseEventArgs)
  285.  
  286.        Me.IsDrawing = False
  287.        Callback.Invoke(SelectedRegion)
  288.        Me.Close() ' Must be called last.
  289.  
  290.    End Sub
  291.  
  292.    ''' <summary>
  293.    ''' Raises the <see cref="E:System.Windows.Forms.Control.MouseMove" /> event.
  294.    ''' </summary>
  295.    ''' <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs" /> that contains the event data.</param>
  296.    Protected Overrides Sub OnMouseMove(ByVal e As MouseEventArgs)
  297.  
  298.        If Me.IsDrawing Then
  299.  
  300.            Me.DrawSize = New Size(e.X - Me.InitialLocation.X, e.Y - Me.InitialLocation.Y)
  301.            Me.DrawRect = New Rectangle(Me.InitialLocation, Me.DrawSize)
  302.  
  303.            If Me.DrawRect.Height < 0 Then
  304.                Me.DrawRect.Height = Math.Abs(Me.DrawRect.Height)
  305.                Me.DrawRect.Y -= Me.DrawRect.Height
  306.            End If
  307.  
  308.            If Me.DrawRect.Width < 0 Then
  309.                Me.DrawRect.Width = Math.Abs(Me.DrawRect.Width)
  310.                Me.DrawRect.X -= Me.DrawRect.Width
  311.            End If
  312.  
  313.            Me.DrawForm.Invalidate()
  314.  
  315.        End If
  316.  
  317.    End Sub
  318.  
  319. #End Region
  320.  
  321. End Class
  322.  
  323. ''' <summary>
  324. ''' Class DrawingRegionClass. This class cannot be inherited.
  325. ''' </summary>
  326. Friend NotInheritable Class DrawingRegionClass : Inherits Form
  327.  
  328.    Private DrawParent As RegionSelector
  329.  
  330.    Public Sub New(ByVal Parent As Form)
  331.  
  332.        Me.DrawParent = Parent
  333.  
  334.    End Sub
  335.  
  336.    Protected Overrides Sub OnPaintBackground(ByVal e As PaintEventArgs)
  337.  
  338.        Dim Bg As Bitmap
  339.        Dim Canvas As Graphics
  340.  
  341.        If Me.DrawParent.IsDrawing Then
  342.  
  343.            Bg = New Bitmap(Width, Height)
  344.            Canvas = Graphics.FromImage(Bg)
  345.            Canvas.Clear(Color.Tomato)
  346.  
  347.            Using pen As New Pen(Me.DrawParent.BorderColor, Me.DrawParent.BorderSize)
  348.                Canvas.DrawRectangle(pen, Me.DrawParent.DrawRect)
  349.            End Using
  350.  
  351.            Canvas.Dispose()
  352.            e.Graphics.DrawImage(Bg, 0, 0, Width, Height)
  353.            Bg.Dispose()
  354.  
  355.        Else
  356.            MyBase.OnPaintBackground(e)
  357.        End If
  358.  
  359.    End Sub
  360.  
  361. End Class


Complemento adicional:

Código
  1.    ' Take Region ScreenShot
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples :
  5.    '
  6.    ' Dim RegionScreenShot As Bitmap = TakeRegionScreenShot(New Point(0, 0), New Size(256, 256))
  7.    ' Dim RegionScreenShot As Bitmap = TakeRegionScreenShot(New Rectangle With {.Location = Point.Empty, .Size = New Size(256, 256)})
  8.    ' PictureBox1.BackgroundImage = RegionScreenShot
  9.    ' RegionScreenShot.Save("C:\RegionScreenShot.png", Imaging.ImageFormat.Png)
  10.    '
  11.    ''' <summary>
  12.    ''' Takes an image screenshot of an specific screen region.
  13.    ''' </summary>
  14.    ''' <param name="Coordinates">
  15.    ''' The X-coordinate is the point at the upper-left corner of the region.
  16.    ''' The Y-coordinate is the point at the upper-left corner of the region.
  17.    ''' </param>
  18.    ''' <param name="Size">Indicates the size of the area to be transferred.</param>
  19.    ''' <param name="PixelFormat">Indicates the Bitmap pixel format.</param>
  20.    ''' <returns>Bitmap.</returns>
  21.    Private Function TakeRegionScreenShot(ByVal Coordinates As Point,
  22.                                          ByVal [Size] As Size,
  23.                                          Optional ByVal [PixelFormat] As Imaging.PixelFormat =
  24.                                                                          Imaging.PixelFormat.Format24bppRgb) As Bitmap
  25.  
  26.        Using ScreenImage As New Bitmap([Size].Width, [Size].Height, [PixelFormat])
  27.  
  28.            Using ScreenGraphics As Graphics = Graphics.FromImage(ScreenImage)
  29.  
  30.                ScreenGraphics.CopyFromScreen(Coordinates, Point.Empty, ScreenImage.Size)
  31.  
  32.            End Using ' ScreenGraphics
  33.  
  34.            Return CType(ScreenImage.Clone, Bitmap)
  35.  
  36.        End Using ' ScreenImage
  37.  
  38.    End Function
  39.  
  40.    ''' <summary>
  41.    ''' Takes an image screenshot of an specific screen region.
  42.    ''' </summary>
  43.    ''' <param name="Region">Indicates a Rectangle structure that contains the region coordinates and the size.</param>
  44.    ''' <param name="PixelFormat">Indicates the Bitmap pixel format.</param>
  45.    ''' <returns>Bitmap.</returns>
  46.    Private Function TakeRegionScreenShot(ByVal [Region] As Rectangle,
  47.                                          Optional ByVal [PixelFormat] As Imaging.PixelFormat =
  48.                                                                          Imaging.PixelFormat.Format24bppRgb) As Bitmap
  49.  
  50.        Return TakeRegionScreenShot([Region].Location, [Region].Size, [PixelFormat])
  51.  
  52.    End Function


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines