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

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


  Mostrar Mensajes
Páginas: 1 ... 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 [687] 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 ... 1236
6861  Programación / .NET (C#, VB.NET, ASP) / Re: Pregunta sobre una aplicación de c# en: 11 Agosto 2014, 21:01 pm
me dice que no se existe en el contecto actual:

Copia y pega aquí el mensaje de la excepción, y comenta cual es el valor que hace saltar dicho error.
6862  Programación / .NET (C#, VB.NET, ASP) / Re: Pregunta sobre una aplicación de c# en: 11 Agosto 2014, 20:55 pm
Código:
mouse_event(MouseEventFlags.ABSOLUTE | MouseEventFlags.MOVE | MouseEventFlags.LEFTDOWN | MouseEventFlags.LEFTUP, PosX, PosY, null, null);

por que cuando los pongo me sale un error de que no están en el contexto actual

Porque en lugar de Constantes yo utilicé una Enum y la llamé 'MouseEventFlags', tu tienes las Constantes definidas, utilizalas:

Código:
MOUSEEVENTF_ABSOLUTE
MOUSEEVENTF_MOVE
MOUSEEVENTF_LEFTDOWN
MOUSEEVENTF_LEFTUP

Si no tienes alguna constante definidia, ya te las mostré en la documentación con los respectivos valores que debes asignarles: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646260%28v=vs.85%29.aspx

+
· enum (C# Reference)
· const (C# Reference)

Si no eres capaz de diferenciar y corregir una minucia como la que te ha ocasioando este problema entonces sin ánimo de ofender te digo que no deberías intentar desarrollar programas de "autoclicks" ni manejarte con la Windows API, debes seguir estudiando y aprender lo básico, no lo quieras poder hacer todo en 1 solo día.

Saludos!
6863  Programación / .NET (C#, VB.NET, ASP) / Re: Pregunta sobre una aplicación de c# en: 11 Agosto 2014, 20:26 pm
Pero yo quiero coordenadas, no quiero que al activar se ponga a dar click el ratón, lo que quiero es que empieza a dar click en un área determinada sin necesidad de que el ratón se mueva.

Lo siento, eso no es lo que me pareció que dijiste al principio:

¿Como puedo hacer que el mouse no se me valla al sitio donde tengo las coordenadas?
La verdad esto no me gusta cuando le activo el mouse se va a las coordenadas y empieza a clickar no ay forma de que no se valla pero si que clike?

De todas formas lee la edición de mi último comentario arriba, solo debes modificar las propiedades de 'cursor.position.x' y 'cursor.position.y' por las coordenadas que quieras.

Saludos
6864  Programación / .NET (C#, VB.NET, ASP) / Re: Pregunta sobre una aplicación de c# en: 11 Agosto 2014, 20:10 pm
No amigo , aun así se me va mueve el cursor mira te paso el codigo entero.

Código:
mouse_event(MOUSEEVENTF_LEFTDOWN, 1290, 317, 0, 0);
            mouse_event(MOUSEEVENTF_LEFTUP, 1290, 317, 0, 0);

1) Imagino que esas coordenadas las asignaste simplemente por probar, pero por si no es así lo comentaré de todas formas:
    Le estás pasando unas coordenadas fijas, no las coordenadas actuales de tu mouse como te indiqué.

2) Si leyeras la documentación del método, la cual te he mostrado 3 o 4 veces ya, verías que los parámetros 'dw' y 'dy' actuan como coordenadas RELATIVAS (es decir, moverse a un offset) a menos que especifiques el flag 'MOUSEEVENTF_ABSOLUTE' en el primer parámetro para que actuen como coordenadas absolutas.

dx & dy:
Citar
The mouse's absolute position along the x-axis or its amount of motion since the last mouse event was generated, depending on the setting of MOUSEEVENTF_ABSOLUTE. Absolute data is specified as the mouse's actual x-coordinate; relative data is specified as the number of mickeys moved. A mickey is the amount that a mouse has to move for it to report that it has moved.

dwflags:
Citar
· MOUSEEVENTF_ABSOLUTE

The dx and dy parameters contain normalized absolute coordinates. If not set, those parameters contain relative data: the change in position since the last reported position. This flag can be set, or not set, regardless of what kind of mouse or mouse-like device, if any, is connected to the system. For further information about relative mouse motion, see the following Remarks section.

Así que debes combinar los flags:
Código
  1. mouse_event(MOUSEEVENTF_LEFTUP | MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, , , ,)

EDITO:
También dice:

Citar
If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535. The event procedure maps these coordinates onto the display surface. Coordinate (0,0) maps onto the upper-left corner of the display surface, (65535,65535) maps onto the lower-right corner.

Así pues, además de combinar los flags debes hacer una operación aritmética para ajustar las coordenadas:

VB.NET
Código
  1. Dim PosX As Integer = ((Cursor.Position.X * 65535I) / Screen.PrimaryScreen.Bounds.Width)
  2. Dim PosY As Integer = ((Cursor.Position.Y * 65535I) / Screen.PrimaryScreen.Bounds.Height)
  3.  
  4. mouse_event(MouseEventFlags.ABSOLUTE Or MouseEventFlags.MOVE Or MouseEventFlags.LEFTDOWN Or MouseEventFlags.LEFTUP,
  5.            PosX, PosY, Nothing, Nothing)

C#:
Código
  1. int PosX = ((Cursor.Position.X * 65535) / Screen.PrimaryScreen.Bounds.Width);
  2. int PosY = ((Cursor.Position.Y * 65535) / Screen.PrimaryScreen.Bounds.Height);
  3.  
  4. mouse_event(MouseEventFlags.ABSOLUTE | MouseEventFlags.MOVE | MouseEventFlags.LEFTDOWN | MouseEventFlags.LEFTUP, PosX, PosY, null, null);
  5.  
  6. //=======================================================
  7. //Service provided by Telerik (www.telerik.com)
  8. //Conversion powered by NRefactory.
  9. //Twitter: @telerik
  10. //Facebook: facebook.com/telerik
  11. //=======================================================
6865  Programación / .NET (C#, VB.NET, ASP) / Re: Mis malas combinaciones :( en: 11 Agosto 2014, 19:29 pm
En la parte de las combinaciones me dice que se esperaba una declaración  ???

resul no esta declarado
palabra no declarado

Luis, si te pido la información de un error no espero escuchar tu versión modificada del mensaje de error, sino el mensaje de error tal cual es, ¿sino como esperas que te ayudemos a depurarlo o encontremos información al respecto? (en este caso no hacia falta buscar nada, con tu explicación fue suficiente intuir el problema, pero la próxima vez quizás no sea tan intuitivo),
no creo que sea tan dificil darle click derecho al error y luego darle al botón de "Copiar" para pegarlo aquí de esta manera:
Código:
'resul' is not declared. It may be inaccessible due to its protection level.

Disulpa pero sabes que soy muy estricto con los detalles, proporcionar la información del error (el mensaje y el stacktrace, sin modificar) es el detalle más importante que se debería tener en cuenta cuando alguien tiene una duda.

Dicho esto, el error se debe a que no has declarado ninguna variable con el nombre 'resul' ni 'palabra', si quieres solucionar el error debes declararlas ...obviamente, jeje.
Código
  1. Dim resul As ¿? = ¿?
  2. Dim palabra As String = ""

Fuera de los Subs tienes declaradas las variables 'Result1', 'Result2' y 'Result3'.
Luego en el bloque del método 'Sumar' tienes una variable 'result' declarada, la 'vida' de esta variable se termina al finalizar el método.
Luego dentro del mismo bloque de 'Sumar' tienes una variable llamada 'Result22' y otra 'Result222'

¿Que lio es ese?, en serio, depeja todo ese lio de variables, colócalas al inicio del código (es decir, fuera de los subs), asígnales un nombre apropiado a cada variable para saber cual es su finalidad y así no dar lugar a equivocaciones, también podrías añadirle un pequeño comentario a cada una de las variables para dejarlo más claro incluso, y luego inizializa cada variable ahí mismo o cuando sea necesario si lo prefieres...

Creo que solo tú te puedes hacerte una idea de que variables deberían ir en 'resul' y 'palabra' para poder corregir esa parte del código que mostraste.

Saludos!
6866  Programación / .NET (C#, VB.NET, ASP) / Re: Pregunta sobre una aplicación de c# en: 11 Agosto 2014, 19:06 pm
La verdad me costo mucho encontrar los codigos y ahora tengo unas cuantas preguntas:

Copiando códigos ni vas a aprender ni mucho menos vas a ser capaz de desarrollar una herramienta rápida/eficaz, deberías cojer un libro/tutorial, leer y practicar hasta que sepas lo más básico.

· C# Programming Guide - MSDN
· C# Tutorials - MSDN

¿Como puedo hacer que el mouse no se me valla al sitio donde tengo las coordenadas?

cuando le activo el mouse se va a las coordenadas y empieza a clickar no ay forma de que no se valla pero si que clike?

Fíjate en esta parte del código:

Citar
Código
  1. // Coordenadas del cursor
  2. Cursor.Position

Las propiedades 'Cursor.Position.X' y 'Cursor.Position.Y' contienen las coordenadas actuales de tu mouse, pásale esas coordenadas a los parámetros 'dx' y 'dy' de la función 'mouse_event'.

Código
  1. mouse_event(MOUSEEVENTF_LEFTDOWN, Cursor.Position.X, Cursor.Position.Y, Nothing, Nothing);
  2. mouse_event(MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, Nothing, Nothing);

(creo que eso debería solucionar el problema)

Saludos!
6867  Programación / .NET (C#, VB.NET, ASP) / Re: C# crear packetlogger? en: 11 Agosto 2014, 18:57 pm
Nadie sabe donde puedo encontrar ayuda?
Por favor por más que busco no encuentro nada al menos si no me pasan código o pagina ayuden a como encontrarlo

· (Definición) Packet Analyzer (Wikipedia)

· (Source) Packet Capture and Analayzer - CodeProject

· (Source) A Network Sniffer in C# - CodeProject

· (Source) SharpPcap - A Packet Capture Framework for .NET - CodeProject

· (Source) How to make a packet logger in C# - RageZone

Y muchos más en Google...

Saludos.
6868  Programación / .NET (C#, VB.NET, ASP) / Re: C# como crear la siguiente aplicación en: 11 Agosto 2014, 18:48 pm
Mas o menos

Pues puedes hacerlo por ejemplo así.

· Si las coordenadas son estáticas entonces puedes simular clicks en dichas coordenadas fijas, con la función 'SendInputs' de la WinAPI (o también puedes seguir usando 'mouse_event')

· Si las coordenadas son dinámicas, puedes utilizar métodos de ImageMatching y/o PixelSearch, puedes desarrollar tu propio algoritmo de búsqueda de píxeles con métodos como 'LockBits', 'UnlockBits' y 'Marshal.Copy', o puedes buscar en Google acerca del tema, hay todo tipo de información y ejemplos ...algunos más malos e ineficientes que otros, los métodos que te dije son los que debes usar a menos que no te importe el rendimiento dle código.
Yo personalmente para el ImageMatching uso la librería de AForge.NET (el namespace Imaging contiene todo lo necesario) el cual tienes un ejemplo d euso aquí: http://foro.elhacker.net/net/aporte_imagematching_buscar_una_imagen_en_la_pantalla_y_devolver_coordenadas-t417393.0.html y para el PixelSearch desarrollé mi propia herramienta la cual puedes encontrar aquí: http://foro.elhacker.net/net/libreria_de_snippets_compartan_aqui_sus_snippets-t378770.0.html;msg1959819#msg1959819

Saludos.
6869  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 11 Agosto 2014, 18:47 pm
Una helper-class para administrar el contenido del archivo HOSTS de Windows:

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 08-11-2014
  4. ' ***********************************************************************
  5. ' <copyright file="HostsFile.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Public Class HostsFileTestClass
  13. '
  14. '    Private Sub HostsFileTestHandler() Handles MyBase.Shown
  15. '
  16. '        ' Instance the HostsFile Class.
  17. '        Dim Hosts As New HostsFile()
  18. '
  19. '        ' Set a new mapping.
  20. '        Dim Mapping As New HostsFile.MappingInfo
  21. '        With Mapping
  22. '            .HostName = "cuantodanio.es"
  23. '            .IP = Hosts.LOCALHOST ' "127.0.0.1"
  24. '            .Comment = "Test mapping comment."
  25. '        End With
  26. '
  27. '        With Hosts
  28. '
  29. '            ' Delete the Host file.
  30. '            If .FileExists Then
  31. '                .FileDelete()
  32. '            End If
  33. '
  34. '            ' Create a new one Hosts file.
  35. '            .FileCreate()
  36. '
  37. '            ' Add some new mappings.
  38. '            .Add(Mapping)
  39. '            .Add(HostName:="www.youtube.com", IP:=.LOCALHOST, Comment:="Test mapping comment")
  40. '
  41. '            ' Check whether a mapping exists.
  42. '            If .IsMapped(Mapping) Then
  43. '                ' Disable the mapping.
  44. '                .Disable(Mapping)
  45. '            End If
  46. '
  47. '            ' Check whether an existing mapping is disabled.
  48. '            If .IsDisabled("www.youtube.com") Then
  49. '                ' Remove the mapping.
  50. '                .Remove("www.youtube.com")
  51. '            End If
  52. '
  53. '            ' Open the HOSTS file with the specified text-editor.
  54. '            .FileOpen("C:\Program Files\Sublime Text\sublime_text.exe")
  55. '
  56. '        End With
  57. '
  58. '        ' Get the IP of a mapped Hostname.
  59. '        MessageBox.Show("cuantodanio.es: " & Hosts.GetMappingFromHostname("cuantodanio.es").IP)
  60. '
  61. '        ' Get all the hostname mappings
  62. '        Dim Mappings As List(Of HostsFile.MappingInfo) = Hosts.GetMappings()
  63. '        For Each MappingInfo As HostsFile.MappingInfo In Mappings
  64. '
  65. '            Dim sb As New System.Text.StringBuilder
  66. '            With sb
  67. '                .AppendLine(String.Format("Hostname...: {0}", MappingInfo.HostName))
  68. '                .AppendLine(String.Format("IP Address.: {0}", MappingInfo.IP))
  69. '                .AppendLine(String.Format("Comment....: {0}", MappingInfo.Comment))
  70. '                .AppendLine(String.Format("Is Enabled?: {0}", Not MappingInfo.IsDisabled))
  71. '            End With
  72. '
  73. '            MessageBox.Show(sb.ToString, "HostsFile Mappings", MessageBoxButtons.OK, MessageBoxIcon.Information)
  74. '
  75. '        Next MappingInfo
  76. '
  77. '        ' Get all the hostname mappings that matches an ip address
  78. '        Dim MappingMatches As List(Of HostsFile.MappingInfo) = Hosts.GetMappingsFromIP(Hosts.LOCALHOST)
  79. '
  80. '    End Sub
  81. '
  82. 'End Class
  83.  
  84. #End Region
  85.  
  86. #Region " Imports "
  87.  
  88. Imports System.IO
  89. Imports System.Net
  90. Imports System.Text
  91.  
  92. #End Region
  93.  
  94. #Region " Hosts File "
  95.  
  96. ''' <summary>
  97. ''' Manages the Windows HOSTS file to map Hostnames to IP addresses.
  98. ''' </summary>
  99. Public Class HostsFile
  100.  
  101. #Region " Constructors "
  102.  
  103.    ''' <summary>
  104.    ''' Initializes a new instance of the <see cref="HostsFile"/> class.
  105.    ''' </summary>
  106.    ''' <param name="HOSTSLocation">
  107.    ''' Optionaly indicates a custom Hosts file location.
  108.    ''' Default value is 'X:\Windows\System32\Drivers\etc\hosts'.
  109.    ''' </param>
  110.    Public Sub New(Optional ByVal HOSTSLocation As String = Nothing)
  111.  
  112.        If Not String.IsNullOrEmpty(HOSTSLocation) Then
  113.            Me._HOSTSLocation = HOSTSLocation
  114.        End If
  115.  
  116.    End Sub
  117.  
  118.    ''' <summary>
  119.    ''' Prevents a default instance of the <see cref="HostsFile"/> class from being created.
  120.    ''' </summary>
  121.    Private Sub New()
  122.    End Sub
  123.  
  124. #End Region
  125.  
  126. #Region " Properties "
  127.  
  128.    ''' <summary>
  129.    ''' The Hosts file location.
  130.    ''' </summary>
  131.    ''' <value>The Hosts file location.</value>
  132.    Public ReadOnly Property HOSTSLocation As String
  133.        Get
  134.            Return _HOSTSLocation
  135.        End Get
  136.    End Property
  137.    Private SysDir As String = Environment.GetFolderPath(Environment.SpecialFolder.System)
  138.    Private _HOSTSLocation As String = Path.Combine(SysDir, "Drivers\etc\hosts")
  139.  
  140.    ''' <summary>
  141.    ''' The Hosts file encoding.
  142.    ''' The encoding must be <see cref="Encoding.Default"/> (ANSI) or <see cref="Encoding.UTF8"/> (UTF-8 without BOM),
  143.    ''' otherwise the entries will be ignored by Windows.
  144.    ''' </summary>
  145.    ''' <value>The Hosts file encoding.</value>
  146.    Public Property HOSTSEncoding As Encoding
  147.        Get
  148.            Return _HOSTSEncoding
  149.        End Get
  150.        Set(ByVal value As Encoding)
  151.            Me._HOSTSEncoding = value
  152.        End Set
  153.    End Property
  154.    Private _HOSTSEncoding As Encoding = Encoding.Default
  155.  
  156.    ''' <summary>
  157.    ''' Gets or sets the default 'LocalHost' IP address.
  158.    ''' In most computers the default address is '127.0.0.1'.
  159.    ''' </summary>
  160.    ''' <value>The default LocalHost.</value>
  161.    Public Property LOCALHOST As String
  162.        Get
  163.            Return Me._LOCALHOST
  164.        End Get
  165.        Set(ByVal value As String)
  166.            Me._LOCALHOST = value
  167.        End Set
  168.    End Property
  169.    Private _LOCALHOST As String = "127.0.0.1"
  170.  
  171.    ''' <summary>
  172.    ''' Gets the default Hosts file header.
  173.    ''' </summary>
  174.    Private ReadOnly HostsHeader As String =
  175. <a><![CDATA[
  176. # Copyright (c) 1993-2009 Microsoft Corp.
  177. #
  178. # This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
  179. #
  180. # This file contains the mappings of IP addresses to host names. Each
  181. # entry should be kept on an individual line. The IP address should
  182. # be placed in the first column followed by the corresponding host name.
  183. # The IP address and the host name should be separated by at least one
  184. # space.
  185. ]]></a>.Value
  186.  
  187. #End Region
  188.  
  189. #Region " Types "
  190.  
  191. #Region " MappingInfo "
  192.  
  193.    ''' <summary>
  194.    ''' Specifies info of a HOSTS file mapping.
  195.    ''' </summary>
  196.    Public Class MappingInfo
  197.  
  198.        ''' <summary>
  199.        ''' Gets or sets the hostname.
  200.        ''' </summary>
  201.        ''' <value>The hostname.</value>
  202.        Public Property HostName As String
  203.  
  204.        ''' <summary>
  205.        ''' Gets or sets the IP address.
  206.        ''' </summary>
  207.        ''' <value>The IP address.</value>
  208.        Public Property IP As String
  209.  
  210.        ''' <summary>
  211.        ''' Gets or sets the mapping comment.
  212.        ''' </summary>
  213.        ''' <value>The mapping comment.</value>
  214.        Public Property Comment As String
  215.  
  216.        ''' <summary>
  217.        ''' This value is reserved.
  218.        ''' Gets a value indicating whether the mapping is disabled in the HOSTS file.
  219.        ''' </summary>
  220.        ''' <value><c>true</c> if the mapping is disabled, <c>false</c> otherwise.</value>
  221.        Public Property IsDisabled As Boolean
  222.  
  223.    End Class
  224.  
  225. #End Region
  226.  
  227. #End Region
  228.  
  229. #Region " Public Methods "
  230.  
  231.    ''' <summary>
  232.    ''' Adds a new mapping.
  233.    ''' </summary>
  234.    ''' <param name="HostName">Indicates the Hostname.</param>
  235.    ''' <param name="IP">Indicates the IP address.</param>
  236.    ''' <param name="Comment">Indicates a comment for this mapping.</param>
  237.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  238.    ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
  239.    ''' <exception cref="System.Exception">Hostname is already mapped.</exception>
  240.    Public Sub Add(ByVal HostName As String,
  241.                   ByVal IP As String,
  242.                   Optional ByVal Comment As String = Nothing)
  243.  
  244.        If Not Me.FileExists() Then ' Hosts file does not exists.
  245.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  246.  
  247.        ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
  248.            Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))
  249.  
  250.        ElseIf Me.IsMapped(HostName) Then ' Hostname is already mapped.
  251.            Throw New Exception(String.Format("Hostname '{0}' is already mapped.", HostName))
  252.  
  253.        Else ' Add the entry.
  254.  
  255.            ' Fix value spacing.
  256.            Dim EntryFormat As String =
  257.                IP & HostName.Insert(0I, ControlChars.Tab) &
  258.                If(Not String.IsNullOrEmpty(Comment),
  259.                   Comment.Insert(0I, ControlChars.Tab & "#"c),
  260.                   String.Empty)
  261.  
  262.            ' Write the mapping.
  263.            File.AppendAllText(Me._HOSTSLocation, Environment.NewLine & EntryFormat, Me._HOSTSEncoding)
  264.  
  265.        End If
  266.  
  267.    End Sub
  268.  
  269.    ''' <summary>
  270.    ''' Adds a new mapping.
  271.    ''' </summary>
  272.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  273.    Public Sub Add(ByVal MappingInfo As MappingInfo)
  274.  
  275.        Me.Add(MappingInfo.HostName, MappingInfo.IP, MappingInfo.Comment)
  276.  
  277.    End Sub
  278.  
  279.    ''' <summary>
  280.    ''' Disables an existing mapping.
  281.    ''' </summary>
  282.    ''' <param name="HostName">Indicates the Hostname.</param>
  283.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  284.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  285.    ''' <exception cref="System.Exception">Hostname is already disabled.</exception>
  286.    Public Sub Disable(ByVal HostName As String)
  287.  
  288.        If Not Me.FileExists() Then ' Hosts file does not exists.
  289.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  290.  
  291.        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
  292.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))
  293.  
  294.        ElseIf Me.IsDisabled(HostName) Then ' Hostname is already disabled.
  295.            Throw New Exception(String.Format("Hostname: '{0}' is already disabled.", HostName))
  296.  
  297.        Else ' Disable the mapping.
  298.  
  299.            ' Retrieve the HOSTS file content.
  300.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  301.  
  302.            ' Iterate the mappings.
  303.            For X As Integer = 0I To (Hosts.Count - 1I)
  304.  
  305.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  306.  
  307.                    ' Retrieve the HostName of this mapping.
  308.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  309.  
  310.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  311.  
  312.                        ' Disable the mapping.
  313.                        Hosts(X) = Hosts(X).Insert(0I, "#"c)
  314.                        Exit For
  315.  
  316.                    End If ' Host.Equals(...)
  317.  
  318.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  319.  
  320.            Next X
  321.  
  322.            File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)
  323.  
  324.        End If
  325.  
  326.    End Sub
  327.  
  328.    ''' <summary>
  329.    ''' Disables an existing mapping.
  330.    ''' </summary>
  331.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  332.    Public Sub Disable(ByVal MappingInfo As MappingInfo)
  333.  
  334.        Me.Disable(MappingInfo.HostName)
  335.  
  336.    End Sub
  337.  
  338.    ''' <summary>
  339.    ''' Removes a mapping.
  340.    ''' </summary>
  341.    ''' <param name="HostName">Indicates the Hostname.</param>
  342.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  343.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  344.    Public Sub Remove(ByVal HostName As String)
  345.  
  346.        If Not Me.FileExists() Then ' Hosts file does not exists.
  347.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  348.  
  349.        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
  350.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))
  351.  
  352.        Else ' Remove the mapping.
  353.  
  354.            ' Retrieve the HOSTS file content.
  355.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  356.  
  357.            ' Iterate the mappings.
  358.            For X As Integer = 0I To (Hosts.Count - 1I)
  359.  
  360.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  361.  
  362.                    ' Retrieve the HostName of this mapping.
  363.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  364.  
  365.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  366.  
  367.                        ' Remove the mapping.
  368.                        Hosts.RemoveAt(X)
  369.                        Exit For
  370.  
  371.                    End If ' Host.Equals(...)
  372.  
  373.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  374.  
  375.            Next X
  376.  
  377.            File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)
  378.  
  379.        End If
  380.  
  381.    End Sub
  382.  
  383.    ''' <summary>
  384.    ''' Removes a mapping.
  385.    ''' </summary>
  386.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  387.    Public Sub Remove(ByVal MappingInfo As MappingInfo)
  388.  
  389.        Me.Remove(MappingInfo.HostName)
  390.  
  391.    End Sub
  392.  
  393.    ''' <summary>
  394.    ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings.
  395.    ''' </summary>
  396.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  397.    Public Function GetMappings() As List(Of MappingInfo)
  398.  
  399.        If Not Me.FileExists() Then ' Hosts file does not exists.
  400.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  401.  
  402.        Else ' Get the mapping.
  403.  
  404.            ' Retrieve the HOSTS file content.
  405.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  406.            Dim Mappings As New List(Of MappingInfo)
  407.  
  408.            ' Iterate the mappings.
  409.            For X As Integer = 0I To (Hosts.Count - 1I)
  410.  
  411.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  412.  
  413.                    ' Retrieve the mapping parts.
  414.                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})
  415.  
  416.                    Dim MappingInfo As New MappingInfo
  417.                    With MappingInfo
  418.                        .HostName = Parts(1I)
  419.                        .IP = Parts(0I).Replace("#"c, String.Empty)
  420.                        .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
  421.                        .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
  422.                    End With ' MappingInfo
  423.  
  424.                    Mappings.Add(MappingInfo)
  425.  
  426.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  427.  
  428.            Next X
  429.  
  430.            Return Mappings
  431.  
  432.        End If
  433.  
  434.    End Function
  435.  
  436.    ''' <summary>
  437.    ''' Gets a <see cref="MappingInfo"/> instance containing the mapping info of a Hostname.
  438.    ''' </summary>
  439.    ''' <param name="HostName">Indicates the Hostname.</param>
  440.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  441.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  442.    Public Function GetMappingFromHostname(ByVal Hostname As String) As MappingInfo
  443.  
  444.        If Not Me.FileExists() Then ' Hosts file does not exists.
  445.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  446.  
  447.        ElseIf Not Me.IsMapped(Hostname) Then ' Hostname is not mapped.
  448.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", Hostname))
  449.  
  450.        Else ' Get the mapping.
  451.  
  452.            ' Retrieve the HOSTS file content.
  453.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  454.            Dim MappingInfo As New MappingInfo
  455.  
  456.            ' Iterate the mappings.
  457.            For X As Integer = 0I To (Hosts.Count - 1I)
  458.  
  459.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  460.  
  461.                    ' Retrieve the mapping parts.
  462.                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})
  463.  
  464.                    If Parts(1I).Equals(Hostname, StringComparison.OrdinalIgnoreCase) Then
  465.  
  466.                        With MappingInfo
  467.                            .HostName = Parts(1I)
  468.                            .IP = Parts(0I).Replace("#"c, String.Empty)
  469.                            .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
  470.                            .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
  471.                        End With ' MappingInfo
  472.  
  473.                        Exit For
  474.  
  475.                    End If ' Parts(1I).Equals(Hostname)...
  476.  
  477.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  478.  
  479.            Next X
  480.  
  481.            Return MappingInfo
  482.  
  483.        End If
  484.  
  485.    End Function
  486.  
  487.    ''' <summary>
  488.    ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings
  489.    ''' matching the specified IP address.
  490.    ''' </summary>
  491.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  492.    ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
  493.    Public Function GetMappingsFromIP(ByVal IP As String) As List(Of MappingInfo)
  494.  
  495.        If Not Me.FileExists() Then ' Hosts file does not exists.
  496.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  497.  
  498.        ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
  499.            Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))
  500.  
  501.        Else ' Get the mapping.
  502.  
  503.            ' Retrieve the HOSTS file content.
  504.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  505.            Dim Mappings As New List(Of MappingInfo)
  506.  
  507.            ' Iterate the mappings.
  508.            For X As Integer = 0I To (Hosts.Count - 1I)
  509.  
  510.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  511.  
  512.                    ' Retrieve the mapping parts.
  513.                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})
  514.  
  515.                    If Parts(0I).Replace("#"c, String.Empty).Equals(IP) Then
  516.  
  517.                        Dim MappingInfo As New MappingInfo
  518.                        With MappingInfo
  519.                            .HostName = Parts(1I)
  520.                            .IP = Parts(0I).Replace("#"c, String.Empty)
  521.                            .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
  522.                            .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
  523.                        End With ' MappingInfo
  524.  
  525.                        Mappings.Add(MappingInfo)
  526.  
  527.                    End If
  528.  
  529.                End If ' Not String.IsNullOrEmpty(Hosts(X))...
  530.  
  531.            Next X
  532.  
  533.            Return Mappings
  534.  
  535.        End If
  536.  
  537.    End Function
  538.  
  539.    ''' <summary>
  540.    ''' Checks whether a HostName is already mapped.
  541.    ''' </summary>
  542.    ''' <param name="HostName">Indicates the Hostname.</param>
  543.    ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
  544.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  545.    Public Function IsMapped(ByVal HostName As String) As Boolean
  546.  
  547.        If Not Me.FileExists() Then ' Hosts file does not exists.
  548.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  549.  
  550.        Else
  551.            ' Retrieve the HOSTS file content.
  552.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  553.  
  554.            ' Iterate the mappings.
  555.            For X As Integer = 0I To (Hosts.Count - 1I)
  556.  
  557.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  558.  
  559.                    ' Retrieve the HostName of this mapping.
  560.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  561.  
  562.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  563.                        Return True
  564.                    End If ' Host.Equals(HostName)...
  565.  
  566.                End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...
  567.  
  568.            Next X
  569.  
  570.            Return False
  571.  
  572.        End If ' Not Me.Exists()...
  573.  
  574.    End Function
  575.  
  576.    ''' <summary>
  577.    ''' Checks whether a HostName is already mapped.
  578.    ''' </summary>
  579.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  580.    ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
  581.    Public Function IsMapped(ByVal MappingInfo As MappingInfo) As Boolean
  582.  
  583.        Return Me.IsMapped(MappingInfo.HostName)
  584.  
  585.    End Function
  586.  
  587.    ''' <summary>
  588.    ''' Checks whether a HostName is already disabled.
  589.    ''' </summary>
  590.    ''' <param name="HostName">Indicates the Hostname.</param>
  591.    ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
  592.    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
  593.    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
  594.    Public Function IsDisabled(ByVal HostName As String) As Boolean
  595.  
  596.        If Not Me.FileExists() Then ' Hosts file does not exists.
  597.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  598.  
  599.        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
  600.            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))
  601.  
  602.        Else
  603.            ' Retrieve the HOSTS file content.
  604.            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
  605.            Dim Result As Boolean = False
  606.  
  607.            ' Iterate the mappings.
  608.            For X As Integer = 0I To (Hosts.Count - 1I)
  609.  
  610.                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then
  611.  
  612.                    ' Retrieve the HostName of this mapping.
  613.                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)
  614.  
  615.                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
  616.                        Result = Hosts(X).TrimStart.StartsWith("#"c)
  617.                        Exit For
  618.                    End If ' Host.Equals(HostName)...
  619.  
  620.                End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...
  621.  
  622.            Next X
  623.  
  624.            Return Result
  625.  
  626.        End If
  627.  
  628.    End Function
  629.  
  630.    ''' <summary>
  631.    ''' Checks whether a HostName is already disabled.
  632.    ''' </summary>
  633.    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
  634.    ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
  635.    Public Function IsDisabled(ByVal MappingInfo As MappingInfo) As Boolean
  636.  
  637.        Return Me.IsDisabled(MappingInfo.HostName)
  638.  
  639.    End Function
  640.  
  641.    ''' <summary>
  642.    ''' Checks whether the Hosts file exists.
  643.    ''' </summary>
  644.    ''' <returns><c>true</c> if Hosts file exists, <c>false</c> otherwise.</returns>
  645.    Public Function FileExists() As Boolean
  646.  
  647.        Return File.Exists(Me._HOSTSLocation)
  648.  
  649.    End Function
  650.  
  651.    ''' <summary>
  652.    ''' Creates the Hosts file.
  653.    ''' </summary>
  654.    Public Sub FileCreate()
  655.  
  656.        If Me.FileExists() Then
  657.            File.Delete(Me._HOSTSLocation)
  658.        End If
  659.  
  660.        File.WriteAllText(Me._HOSTSLocation, Me.HostsHeader, Me._HOSTSEncoding)
  661.  
  662.    End Sub
  663.  
  664.    ''' <summary>
  665.    ''' Deletes the Hosts file.
  666.    ''' </summary>
  667.    ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
  668.    Public Sub FileDelete()
  669.  
  670.        If Not Me.FileExists() Then
  671.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  672.  
  673.        Else
  674.            File.Delete(Me._HOSTSLocation)
  675.  
  676.        End If
  677.  
  678.    End Sub
  679.  
  680.    ''' <summary>
  681.    ''' Cleans the Hosts file.
  682.    ''' This removes all the mappings and adds the default file header.
  683.    ''' </summary>
  684.    Public Sub FileClean()
  685.  
  686.        Me.FileCreate()
  687.  
  688.    End Sub
  689.  
  690.    ''' <summary>
  691.    ''' Opens the Hosts file with the specified process.
  692.    ''' </summary>
  693.    ''' <param name="Process">
  694.    ''' Indicates the process location.
  695.    ''' Default value is: "notepad.exe".
  696.    ''' </param>
  697.    ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
  698.    ''' <exception cref="System.IO.FileNotFoundException">Process not found.</exception>
  699.    Public Sub FileOpen(Optional ByVal Process As String = "notepad.exe")
  700.  
  701.        If Not Me.FileExists Then
  702.            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)
  703.  
  704.        ElseIf Not File.Exists(Process) Then
  705.            Throw New FileNotFoundException("Process not found.", Process)
  706.  
  707.        Else
  708.            Diagnostics.Process.Start(Process, ControlChars.Quote & Me._HOSTSLocation & ControlChars.Quote)
  709.  
  710.        End If
  711.  
  712.    End Sub
  713.  
  714. #End Region
  715.  
  716. #Region " Private Methods "
  717.  
  718.    ''' <summary>
  719.    ''' Validates an IP address.
  720.    ''' </summary>
  721.    ''' <param name="Address">The IP address.</param>
  722.    ''' <returns><c>true</c> if IP is in the proper format, <c>false</c> otherwise.</returns>
  723.    Private Function ValidateIP(ByVal Address As String) As Boolean
  724.  
  725.        Dim IP As IPAddress = Nothing
  726.        Return IPAddress.TryParse(Address, IP)
  727.  
  728.    End Function
  729.  
  730. #End Region
  731.  
  732. End Class
  733.  
  734. #End Region
6870  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 11 Agosto 2014, 18:46 pm
una Helper-Class para procesar los pixeles de una imagen, buscar un color especifico y devolver las coordenadas, obtener un rango de píxeles, etc.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 07-11-2014
  4. ' ***********************************************************************
  5. ' <copyright file="PixelUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12.  
  13. ' **************************************************
  14. ' Count the number of Pixels that contains the image
  15. ' **************************************************
  16. '
  17. '' Create a new bitmap.
  18. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
  19. '
  20. '' Instance a PixelUtil Class.
  21. 'Dim bmpPixelUtil As New PixelUtil(bmp)
  22. '
  23. '' Display the pixel count.
  24. 'MessageBox.Show(String.Format("Total amount of Pixels: {0}", CStr(bmpPixelUtil.PixelCount)))
  25.  
  26.  
  27. ' ************************************************
  28. ' Searchs for an specific pixel color in the image
  29. ' ************************************************
  30. '
  31. '' Create a new bitmap.
  32. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
  33. '
  34. '' Instance a PixelUtil Class.
  35. 'Dim bmpPixelUtil As New PixelUtil(bmp)
  36. '
  37. '' Specify the RGB PixelColor to search.
  38. 'Dim FindColor As Color = Color.FromArgb(255, 174, 201)
  39. '
  40. '' Get the pixel data.
  41. 'Dim FoundPixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.SearchColor(FindColor)
  42. '
  43. '' Loop through each pixel.
  44. 'For Each Pixel As PixelUtil.PixelData In FoundPixels
  45. '
  46. '    Dim sb As New System.Text.StringBuilder
  47. '    With sb
  48. '
  49. '        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
  50. '        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
  51. '
  52. '        MessageBox.Show(.ToString, "Pixel-Color Search")
  53. '
  54. '        .Clear()
  55. '
  56. '    End With
  57. '
  58. 'Next Pixel
  59.  
  60.  
  61. ' *********************************************************************
  62. ' Retrieve the index, color, and coordinates of each pixel in the image
  63. ' *********************************************************************
  64. '
  65. '' Create a new bitmap.
  66. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
  67. '
  68. '' Instance a PixelUtil Class.
  69. 'Dim bmpPixelUtil As New PixelUtil(bmp)
  70. '
  71. '' Get the pixel data.
  72. 'Dim Pixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.GetPixelData()
  73. '
  74. '' Loop through each pixel.
  75. 'For Each Pixel As PixelUtil.PixelData In Pixels
  76. '
  77. '    Dim sb As New System.Text.StringBuilder
  78. '    With sb
  79. '
  80. '        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
  81. '        .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString))
  82. '        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
  83. '
  84. '        MessageBox.Show(.ToString, "Pixel Search")
  85. '
  86. '        .Clear()
  87. '
  88. '    End With
  89. '
  90. 'Next Pixel
  91.  
  92.  
  93. ' ****************************************************************************
  94. ' Retrieve the index, color, and coordinates of a range of pixels in the image
  95. ' ****************************************************************************
  96. '
  97. '' Create a new bitmap.
  98. 'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
  99. '
  100. '' Instance a PixelUtil Class.
  101. 'Dim bmpPixelUtil As New PixelUtil(bmp)
  102. '
  103. '' Specify the pixel range to retrieve.
  104. 'Dim RangeMin As Integer = 1919I
  105. 'Dim RangeMax As Integer = 1921I
  106. '
  107. '' Get the pixel data.
  108. 'Dim FoundPixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.GetPixelData(RangeMin, RangeMax)
  109. '
  110. '' Loop through each pixel.
  111. 'For Each Pixel As PixelUtil.PixelData In FoundPixels
  112. '
  113. '    Dim sb As New System.Text.StringBuilder
  114. '    With sb
  115. '
  116. '        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
  117. '        .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString))
  118. '        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
  119. '
  120. '        MessageBox.Show(.ToString, "Pixel-Color Search")
  121. '
  122. '        .Clear()
  123. '
  124. '    End With
  125. '
  126. 'Next Pixel
  127.  
  128.  
  129. #End Region
  130.  
  131. #Region " Imports "
  132.  
  133. Imports System.ComponentModel
  134. Imports System.Drawing.Imaging
  135. Imports System.Runtime.InteropServices
  136.  
  137. #End Region
  138.  
  139. #Region " PixelUtil "
  140.  
  141. Public Class PixelUtil
  142.  
  143. #Region " Vars, Properties "
  144.  
  145.    Private _PixelData As List(Of PixelData) = Nothing
  146.    Private _bmp As Bitmap = Nothing
  147.    Private _PixelCount As Integer = Nothing
  148.  
  149.    ''' <summary>
  150.    ''' Gets the Bitmap object.
  151.    ''' </summary>
  152.    ''' <value>The BMP.</value>
  153.    Public ReadOnly Property bmp As Bitmap
  154.        Get
  155.            Return Me._bmp
  156.        End Get
  157.    End Property
  158.  
  159.    ''' <summary>
  160.    ''' Gets the total amount of pixels that contains the Bitmap.
  161.    ''' </summary>
  162.    ''' <value>The pixel count.</value>
  163.    Public ReadOnly Property PixelCount As Integer
  164.        Get
  165.            Return Me._PixelCount
  166.        End Get
  167.    End Property
  168.  
  169. #End Region
  170.  
  171. #Region " Classes "
  172.  
  173.    ''' <summary>
  174.    ''' Stores specific pixel information of an image.
  175.    ''' </summary>
  176.    Public Class PixelData
  177.  
  178.        ''' <summary>
  179.        ''' Gets or sets the pixel index.
  180.        ''' </summary>
  181.        ''' <value>The pixel index.</value>
  182.        Public Property Index As Integer
  183.  
  184.        ''' <summary>
  185.        ''' Gets or sets the pixel color.
  186.        ''' </summary>
  187.        ''' <value>The pixel color.</value>
  188.        Public Property Color As Color
  189.  
  190.        ''' <summary>
  191.        ''' Gets or sets the pixel coordinates relative to the image.
  192.        ''' </summary>
  193.        ''' <value>The pixel coordinates.</value>
  194.        Public Property Coordinates As Point
  195.  
  196.    End Class
  197.  
  198. #End Region
  199.  
  200. #Region " Constructors "
  201.  
  202.    ''' <summary>
  203.    ''' Prevents a default instance of the <see cref="PixelUtil"/> class from being created.
  204.    ''' </summary>
  205.    Private Sub New()
  206.    End Sub
  207.  
  208.    ''' <summary>
  209.    ''' Initializes a new instance of the <see cref="PixelUtil"/> class.
  210.    ''' </summary>
  211.    ''' <param name="bmp">Indicates the Bitmap image to process it's pixels.</param>
  212.    ''' <exception cref="System.Exception">PixelFormat unsupported.</exception>
  213.    Public Sub New(ByVal bmp As Bitmap)
  214.  
  215.        If Not bmp.PixelFormat = PixelFormat.Format24bppRgb Then
  216.            Throw New Exception("PixelFormat unsupported.")
  217.        End If
  218.  
  219.        Me._bmp = bmp
  220.        Me._PixelCount = Me.[Count]
  221.  
  222.    End Sub
  223.  
  224. #End Region
  225.  
  226. #Region " Public Methods "
  227.  
  228.    ''' <summary>
  229.    ''' Returns a <c>'PixelData'</c> object containing information about each pixel in the image.
  230.    ''' </summary>
  231.    ''' <returns>List(Of PixelData).</returns>
  232.    Public Function GetPixelData() As List(Of PixelData)
  233.  
  234.        If Me._PixelData Is Nothing Then
  235.  
  236.            Me._PixelData = New List(Of PixelData)
  237.  
  238.            ' Lock the Bitmap bits.
  239.            Dim bmpRect As New Rectangle(0, 0, Me._bmp.Width, Me._bmp.Height)
  240.            Dim bmpData As BitmapData = Me._bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, Me._bmp.PixelFormat)
  241.  
  242.            ' Get the address of the first line.
  243.            Dim Pointer As IntPtr = bmpData.Scan0
  244.  
  245.            ' Hold the bytes of the bitmap into a Byte-Array.
  246.            ' NOTE: This code is specific to a bitmap with 24 bits per pixels.
  247.            Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height)
  248.            Dim rgbData(bmpBytes - 1) As Byte
  249.  
  250.            ' Copy the RGB values into the array.
  251.            Marshal.Copy(Pointer, rgbData, 0, bmpBytes)
  252.  
  253.            ' Unlock the Bitmap bits.
  254.            Me._bmp.UnlockBits(bmpData)
  255.  
  256.            ' Loop through each 24bpp-RGB value.
  257.            For rgbIndex As Integer = 2 To rgbData.Length - 1 Step 3
  258.  
  259.                ' Set the pixel Data.
  260.                Dim Pixel As New PixelData
  261.  
  262.                With Pixel
  263.  
  264.                    .Index = rgbIndex \ 3I
  265.  
  266.                    .Color = Color.FromArgb(red:=rgbData(rgbIndex),
  267.                                            green:=rgbData(rgbIndex - 1I),
  268.                                            blue:=rgbData(rgbIndex - 2I))
  269.  
  270.                    .Coordinates = New Point(X:=(.Index Mod bmpRect.Width),
  271.                                             Y:=(.Index - (.Index Mod bmpRect.Width)) \ bmpRect.Width)
  272.  
  273.                End With
  274.  
  275.                ' Add the PixelData into the list.
  276.                Me._PixelData.Add(Pixel)
  277.  
  278.            Next rgbIndex
  279.  
  280.        End If
  281.  
  282.        Return Me._PixelData
  283.  
  284.    End Function
  285.  
  286.    ''' <summary>
  287.    ''' Returns a <c>'PixelData'</c> object containing information about a range of pixels in the image.
  288.    ''' </summary>
  289.    ''' <returns>List(Of PixelData).</returns>
  290.    ''' <exception cref="System.Exception">Pixel index is out of range</exception>
  291.    Public Function GetPixelData(ByVal RangeMin As Integer,
  292.                                 ByVal RangeMax As Integer) As List(Of PixelData)
  293.  
  294.        If Not (Me._PixelCount >= RangeMin AndAlso Me._PixelCount <= RangeMax) Then
  295.            Throw New Exception("Pixel index is out of range.")
  296.            Return Nothing
  297.        End If
  298.  
  299.        ' Return the Pixel range.
  300.        Return (From Pixel As PixelData In Me.GetPixelData()
  301.                Where (Pixel.Index >= RangeMin AndAlso Pixel.Index <= RangeMax)).ToList
  302.  
  303.    End Function
  304.  
  305.    ''' <summary>
  306.    ''' Searchs for the specified pixel-color inside the image and returns all the matches.
  307.    ''' </summary>
  308.    ''' <param name="PixelColor">Indicates the color to find.</param>
  309.    ''' <returns>List(Of PixelData).</returns>
  310.    Public Function SearchColor(ByVal PixelColor As Color) As List(Of PixelData)
  311.  
  312.        Return (From Pixel As PixelData In Me.GetPixelData
  313.                Where Pixel.Color = PixelColor).ToList
  314.  
  315.    End Function
  316.  
  317. #End Region
  318.  
  319. #Region " Private Methods "
  320.  
  321.    ''' <summary>
  322.    ''' Counts the number of pixels that contains the image.
  323.    ''' </summary>
  324.    ''' <returns>The number of pixels.</returns>
  325.    Private Function [Count]() As Integer
  326.  
  327.        ' Lock the Bitmap bits.
  328.        Dim bmpRect As New Rectangle(0, 0, Me._bmp.Width, Me._bmp.Height)
  329.        Dim bmpData As BitmapData = Me._bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, Me._bmp.PixelFormat)
  330.  
  331.        ' Get the address of the first line.
  332.        Dim Pointer As IntPtr = bmpData.Scan0
  333.  
  334.        ' Hold the bytes of the bitmap into a Byte-Array.
  335.        ' NOTE: This code is specific to a bitmap with 24 bits per pixels.
  336.        Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height)
  337.        Dim rgbData(bmpBytes - 1) As Byte
  338.  
  339.        ' Copy the RGB values into the array.
  340.        Marshal.Copy(Pointer, rgbData, 0, bmpBytes)
  341.  
  342.        ' Unlock the Bitmap bits.
  343.        Me._bmp.UnlockBits(bmpData)
  344.  
  345.        Return rgbData.Count
  346.  
  347.    End Function
  348.  
  349. #End Region
  350.  
  351. #Region " Hidden Methods "
  352.  
  353.    ''' <summary>
  354.    ''' Serves as a hash function for a particular type.
  355.    ''' </summary>
  356.    <EditorBrowsable(EditorBrowsableState.Never)>
  357.    Public Shadows Sub GetHashCode()
  358.    End Sub
  359.  
  360.    ''' <summary>
  361.    ''' Determines whether the specified System.Object is equal to the current System.Object.
  362.    ''' </summary>
  363.    <EditorBrowsable(EditorBrowsableState.Never)>
  364.    Public Shadows Sub Equals()
  365.    End Sub
  366.  
  367.    ''' <summary>
  368.    ''' Returns a String that represents the current object.
  369.    ''' </summary>
  370.    <EditorBrowsable(EditorBrowsableState.Never)>
  371.    Public Shadows Sub ToString()
  372.    End Sub
  373.  
  374. #End Region
  375.  
  376. End Class
  377.  
  378. #End Region
  379.  
Páginas: 1 ... 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 [687] 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines