Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - Eleкtro

#6731
Cita de: andrecid en 10 Agosto 2014, 22:01 PMMas 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.
#6732
Una helper-class para administrar el contenido del archivo HOSTS de Windows:

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 08-11-2014
' ***********************************************************************
' <copyright file="HostsFile.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

'Public Class HostsFileTestClass
'
'    Private Sub HostsFileTestHandler() Handles MyBase.Shown
'
'        ' Instance the HostsFile Class.
'        Dim Hosts As New HostsFile()
'
'        ' Set a new mapping.
'        Dim Mapping As New HostsFile.MappingInfo
'        With Mapping
'            .HostName = "cuantodanio.es"
'            .IP = Hosts.LOCALHOST ' "127.0.0.1"
'            .Comment = "Test mapping comment."
'        End With
'
'        With Hosts
'
'            ' Delete the Host file.
'            If .FileExists Then
'                .FileDelete()
'            End If
'
'            ' Create a new one Hosts file.
'            .FileCreate()
'
'            ' Add some new mappings.
'            .Add(Mapping)
'            .Add(HostName:="www.youtube.com", IP:=.LOCALHOST, Comment:="Test mapping comment")
'
'            ' Check whether a mapping exists.
'            If .IsMapped(Mapping) Then
'                ' Disable the mapping.
'                .Disable(Mapping)
'            End If
'
'            ' Check whether an existing mapping is disabled.
'            If .IsDisabled("www.youtube.com") Then
'                ' Remove the mapping.
'                .Remove("www.youtube.com")
'            End If
'
'            ' Open the HOSTS file with the specified text-editor.
'            .FileOpen("C:\Program Files\Sublime Text\sublime_text.exe")
'
'        End With
'
'        ' Get the IP of a mapped Hostname.
'        MessageBox.Show("cuantodanio.es: " & Hosts.GetMappingFromHostname("cuantodanio.es").IP)
'
'        ' Get all the hostname mappings
'        Dim Mappings As List(Of HostsFile.MappingInfo) = Hosts.GetMappings()
'        For Each MappingInfo As HostsFile.MappingInfo In Mappings
'
'            Dim sb As New System.Text.StringBuilder
'            With sb
'                .AppendLine(String.Format("Hostname...: {0}", MappingInfo.HostName))
'                .AppendLine(String.Format("IP Address.: {0}", MappingInfo.IP))
'                .AppendLine(String.Format("Comment....: {0}", MappingInfo.Comment))
'                .AppendLine(String.Format("Is Enabled?: {0}", Not MappingInfo.IsDisabled))
'            End With
'
'            MessageBox.Show(sb.ToString, "HostsFile Mappings", MessageBoxButtons.OK, MessageBoxIcon.Information)
'
'        Next MappingInfo
'
'        ' Get all the hostname mappings that matches an ip address
'        Dim MappingMatches As List(Of HostsFile.MappingInfo) = Hosts.GetMappingsFromIP(Hosts.LOCALHOST)
'
'    End Sub
'
'End Class

#End Region

#Region " Imports "

Imports System.IO
Imports System.Net
Imports System.Text

#End Region

#Region " Hosts File "

''' <summary>
''' Manages the Windows HOSTS file to map Hostnames to IP addresses.
''' </summary>
Public Class HostsFile

#Region " Constructors "

    ''' <summary>
    ''' Initializes a new instance of the <see cref="HostsFile"/> class.
    ''' </summary>
    ''' <param name="HOSTSLocation">
    ''' Optionaly indicates a custom Hosts file location.
    ''' Default value is 'X:\Windows\System32\Drivers\etc\hosts'.
    ''' </param>
    Public Sub New(Optional ByVal HOSTSLocation As String = Nothing)

        If Not String.IsNullOrEmpty(HOSTSLocation) Then
            Me._HOSTSLocation = HOSTSLocation
        End If

    End Sub

    ''' <summary>
    ''' Prevents a default instance of the <see cref="HostsFile"/> class from being created.
    ''' </summary>
    Private Sub New()
    End Sub

#End Region

#Region " Properties "

    ''' <summary>
    ''' The Hosts file location.
    ''' </summary>
    ''' <value>The Hosts file location.</value>
    Public ReadOnly Property HOSTSLocation As String
        Get
            Return _HOSTSLocation
        End Get
    End Property
    Private SysDir As String = Environment.GetFolderPath(Environment.SpecialFolder.System)
    Private _HOSTSLocation As String = Path.Combine(SysDir, "Drivers\etc\hosts")

    ''' <summary>
    ''' The Hosts file encoding.
    ''' The encoding must be <see cref="Encoding.Default"/> (ANSI) or <see cref="Encoding.UTF8"/> (UTF-8 without BOM),
    ''' otherwise the entries will be ignored by Windows.
    ''' </summary>
    ''' <value>The Hosts file encoding.</value>
    Public Property HOSTSEncoding As Encoding
        Get
            Return _HOSTSEncoding
        End Get
        Set(ByVal value As Encoding)
            Me._HOSTSEncoding = value
        End Set
    End Property
    Private _HOSTSEncoding As Encoding = Encoding.Default

    ''' <summary>
    ''' Gets or sets the default 'LocalHost' IP address.
    ''' In most computers the default address is '127.0.0.1'.
    ''' </summary>
    ''' <value>The default LocalHost.</value>
    Public Property LOCALHOST As String
        Get
            Return Me._LOCALHOST
        End Get
        Set(ByVal value As String)
            Me._LOCALHOST = value
        End Set
    End Property
    Private _LOCALHOST As String = "127.0.0.1"

    ''' <summary>
    ''' Gets the default Hosts file header.
    ''' </summary>
    Private ReadOnly HostsHeader As String =
<a><![CDATA[
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
]]></a>.Value

#End Region

#Region " Types "

#Region " MappingInfo "

    ''' <summary>
    ''' Specifies info of a HOSTS file mapping.
    ''' </summary>
    Public Class MappingInfo

        ''' <summary>
        ''' Gets or sets the hostname.
        ''' </summary>
        ''' <value>The hostname.</value>
        Public Property HostName As String

        ''' <summary>
        ''' Gets or sets the IP address.
        ''' </summary>
        ''' <value>The IP address.</value>
        Public Property IP As String

        ''' <summary>
        ''' Gets or sets the mapping comment.
        ''' </summary>
        ''' <value>The mapping comment.</value>
        Public Property Comment As String

        ''' <summary>
        ''' This value is reserved.
        ''' Gets a value indicating whether the mapping is disabled in the HOSTS file.
        ''' </summary>
        ''' <value><c>true</c> if the mapping is disabled, <c>false</c> otherwise.</value>
        Public Property IsDisabled As Boolean

    End Class

#End Region

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Adds a new mapping.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <param name="IP">Indicates the IP address.</param>
    ''' <param name="Comment">Indicates a comment for this mapping.</param>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
    ''' <exception cref="System.Exception">Hostname is already mapped.</exception>
    Public Sub Add(ByVal HostName As String,
                   ByVal IP As String,
                   Optional ByVal Comment As String = Nothing)

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
            Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))

        ElseIf Me.IsMapped(HostName) Then ' Hostname is already mapped.
            Throw New Exception(String.Format("Hostname '{0}' is already mapped.", HostName))

        Else ' Add the entry.

            ' Fix value spacing.
            Dim EntryFormat As String =
                IP & HostName.Insert(0I, ControlChars.Tab) &
                If(Not String.IsNullOrEmpty(Comment),
                   Comment.Insert(0I, ControlChars.Tab & "#"c),
                   String.Empty)

            ' Write the mapping.
            File.AppendAllText(Me._HOSTSLocation, Environment.NewLine & EntryFormat, Me._HOSTSEncoding)

        End If

    End Sub

    ''' <summary>
    ''' Adds a new mapping.
    ''' </summary>
    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
    Public Sub Add(ByVal MappingInfo As MappingInfo)

        Me.Add(MappingInfo.HostName, MappingInfo.IP, MappingInfo.Comment)

    End Sub

    ''' <summary>
    ''' Disables an existing mapping.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
    ''' <exception cref="System.Exception">Hostname is already disabled.</exception>
    Public Sub Disable(ByVal HostName As String)

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))

        ElseIf Me.IsDisabled(HostName) Then ' Hostname is already disabled.
            Throw New Exception(String.Format("Hostname: '{0}' is already disabled.", HostName))

        Else ' Disable the mapping.

            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the HostName of this mapping.
                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then

                        ' Disable the mapping.
                        Hosts(X) = Hosts(X).Insert(0I, "#"c)
                        Exit For

                    End If ' Host.Equals(...)

                End If ' Not String.IsNullOrEmpty(Hosts(X))...

            Next X

            File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)

        End If

    End Sub

    ''' <summary>
    ''' Disables an existing mapping.
    ''' </summary>
    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
    Public Sub Disable(ByVal MappingInfo As MappingInfo)

        Me.Disable(MappingInfo.HostName)

    End Sub

    ''' <summary>
    ''' Removes a mapping.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
    Public Sub Remove(ByVal HostName As String)

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))

        Else ' Remove the mapping.

            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the HostName of this mapping.
                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then

                        ' Remove the mapping.
                        Hosts.RemoveAt(X)
                        Exit For

                    End If ' Host.Equals(...)

                End If ' Not String.IsNullOrEmpty(Hosts(X))...

            Next X

            File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)

        End If

    End Sub

    ''' <summary>
    ''' Removes a mapping.
    ''' </summary>
    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
    Public Sub Remove(ByVal MappingInfo As MappingInfo)

        Me.Remove(MappingInfo.HostName)

    End Sub

    ''' <summary>
    ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings.
    ''' </summary>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    Public Function GetMappings() As List(Of MappingInfo)

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        Else ' Get the mapping.

            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
            Dim Mappings As New List(Of MappingInfo)

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the mapping parts.
                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})

                    Dim MappingInfo As New MappingInfo
                    With MappingInfo
                        .HostName = Parts(1I)
                        .IP = Parts(0I).Replace("#"c, String.Empty)
                        .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
                        .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
                    End With ' MappingInfo

                    Mappings.Add(MappingInfo)

                End If ' Not String.IsNullOrEmpty(Hosts(X))...

            Next X

            Return Mappings

        End If

    End Function

    ''' <summary>
    ''' Gets a <see cref="MappingInfo"/> instance containing the mapping info of a Hostname.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
    Public Function GetMappingFromHostname(ByVal Hostname As String) As MappingInfo

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.IsMapped(Hostname) Then ' Hostname is not mapped.
            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", Hostname))

        Else ' Get the mapping.

            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
            Dim MappingInfo As New MappingInfo

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the mapping parts.
                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})

                    If Parts(1I).Equals(Hostname, StringComparison.OrdinalIgnoreCase) Then

                        With MappingInfo
                            .HostName = Parts(1I)
                            .IP = Parts(0I).Replace("#"c, String.Empty)
                            .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
                            .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
                        End With ' MappingInfo

                        Exit For

                    End If ' Parts(1I).Equals(Hostname)...

                End If ' Not String.IsNullOrEmpty(Hosts(X))...

            Next X

            Return MappingInfo

        End If

    End Function

    ''' <summary>
    ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings
    ''' matching the specified IP address.
    ''' </summary>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
    Public Function GetMappingsFromIP(ByVal IP As String) As List(Of MappingInfo)

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
            Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))

        Else ' Get the mapping.

            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
            Dim Mappings As New List(Of MappingInfo)

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the mapping parts.
                    Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})

                    If Parts(0I).Replace("#"c, String.Empty).Equals(IP) Then

                        Dim MappingInfo As New MappingInfo
                        With MappingInfo
                            .HostName = Parts(1I)
                            .IP = Parts(0I).Replace("#"c, String.Empty)
                            .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
                            .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
                        End With ' MappingInfo

                        Mappings.Add(MappingInfo)

                    End If

                End If ' Not String.IsNullOrEmpty(Hosts(X))...

            Next X

            Return Mappings

        End If

    End Function

    ''' <summary>
    ''' Checks whether a HostName is already mapped.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    Public Function IsMapped(ByVal HostName As String) As Boolean

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        Else
            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the HostName of this mapping.
                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
                        Return True
                    End If ' Host.Equals(HostName)...

                End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...

            Next X

            Return False

        End If ' Not Me.Exists()...

    End Function

    ''' <summary>
    ''' Checks whether a HostName is already mapped.
    ''' </summary>
    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
    ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
    Public Function IsMapped(ByVal MappingInfo As MappingInfo) As Boolean

        Return Me.IsMapped(MappingInfo.HostName)

    End Function

    ''' <summary>
    ''' Checks whether a HostName is already disabled.
    ''' </summary>
    ''' <param name="HostName">Indicates the Hostname.</param>
    ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
    ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
    ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
    Public Function IsDisabled(ByVal HostName As String) As Boolean

        If Not Me.FileExists() Then ' Hosts file does not exists.
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
            Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))

        Else
            ' Retrieve the HOSTS file content.
            Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
            Dim Result As Boolean = False

            ' Iterate the mappings.
            For X As Integer = 0I To (Hosts.Count - 1I)

                If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                    ' Retrieve the HostName of this mapping.
                    Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                    If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
                        Result = Hosts(X).TrimStart.StartsWith("#"c)
                        Exit For
                    End If ' Host.Equals(HostName)...

                End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...

            Next X

            Return Result

        End If

    End Function

    ''' <summary>
    ''' Checks whether a HostName is already disabled.
    ''' </summary>
    ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
    ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
    Public Function IsDisabled(ByVal MappingInfo As MappingInfo) As Boolean

        Return Me.IsDisabled(MappingInfo.HostName)

    End Function

    ''' <summary>
    ''' Checks whether the Hosts file exists.
    ''' </summary>
    ''' <returns><c>true</c> if Hosts file exists, <c>false</c> otherwise.</returns>
    Public Function FileExists() As Boolean

        Return File.Exists(Me._HOSTSLocation)

    End Function

    ''' <summary>
    ''' Creates the Hosts file.
    ''' </summary>
    Public Sub FileCreate()

        If Me.FileExists() Then
            File.Delete(Me._HOSTSLocation)
        End If

        File.WriteAllText(Me._HOSTSLocation, Me.HostsHeader, Me._HOSTSEncoding)

    End Sub

    ''' <summary>
    ''' Deletes the Hosts file.
    ''' </summary>
    ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
    Public Sub FileDelete()

        If Not Me.FileExists() Then
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        Else
            File.Delete(Me._HOSTSLocation)

        End If

    End Sub

    ''' <summary>
    ''' Cleans the Hosts file.
    ''' This removes all the mappings and adds the default file header.
    ''' </summary>
    Public Sub FileClean()

        Me.FileCreate()

    End Sub

    ''' <summary>
    ''' Opens the Hosts file with the specified process.
    ''' </summary>
    ''' <param name="Process">
    ''' Indicates the process location.
    ''' Default value is: "notepad.exe".
    ''' </param>
    ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
    ''' <exception cref="System.IO.FileNotFoundException">Process not found.</exception>
    Public Sub FileOpen(Optional ByVal Process As String = "notepad.exe")

        If Not Me.FileExists Then
            Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

        ElseIf Not File.Exists(Process) Then
            Throw New FileNotFoundException("Process not found.", Process)

        Else
            Diagnostics.Process.Start(Process, ControlChars.Quote & Me._HOSTSLocation & ControlChars.Quote)

        End If

    End Sub

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Validates an IP address.
    ''' </summary>
    ''' <param name="Address">The IP address.</param>
    ''' <returns><c>true</c> if IP is in the proper format, <c>false</c> otherwise.</returns>
    Private Function ValidateIP(ByVal Address As String) As Boolean

        Dim IP As IPAddress = Nothing
        Return IPAddress.TryParse(Address, IP)

    End Function

#End Region

End Class

#End Region
#6733
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 (vbnet) [Seleccionar]

' ***********************************************************************
' Author           : Elektro
' Last Modified On : 07-11-2014
' ***********************************************************************
' <copyright file="PixelUtil.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "


' **************************************************
' Count the number of Pixels that contains the image
' **************************************************
'
'' Create a new bitmap.
'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
'
'' Instance a PixelUtil Class.
'Dim bmpPixelUtil As New PixelUtil(bmp)
'
'' Display the pixel count.
'MessageBox.Show(String.Format("Total amount of Pixels: {0}", CStr(bmpPixelUtil.PixelCount)))


' ************************************************
' Searchs for an specific pixel color in the image
' ************************************************
'
'' Create a new bitmap.
'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
'
'' Instance a PixelUtil Class.
'Dim bmpPixelUtil As New PixelUtil(bmp)
'
'' Specify the RGB PixelColor to search.
'Dim FindColor As Color = Color.FromArgb(255, 174, 201)
'
'' Get the pixel data.
'Dim FoundPixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.SearchColor(FindColor)
'
'' Loop through each pixel.
'For Each Pixel As PixelUtil.PixelData In FoundPixels
'
'    Dim sb As New System.Text.StringBuilder
'    With sb
'
'        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
'        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
'
'        MessageBox.Show(.ToString, "Pixel-Color Search")
'
'        .Clear()
'
'    End With
'
'Next Pixel


' *********************************************************************
' Retrieve the index, color, and coordinates of each pixel in the image
' *********************************************************************
'
'' Create a new bitmap.
'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
'
'' Instance a PixelUtil Class.
'Dim bmpPixelUtil As New PixelUtil(bmp)
'
'' Get the pixel data.
'Dim Pixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.GetPixelData()
'
'' Loop through each pixel.
'For Each Pixel As PixelUtil.PixelData In Pixels
'
'    Dim sb As New System.Text.StringBuilder
'    With sb
'
'        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
'        .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString))
'        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
'
'        MessageBox.Show(.ToString, "Pixel Search")
'
'        .Clear()
'
'    End With
'
'Next Pixel


' ****************************************************************************
' Retrieve the index, color, and coordinates of a range of pixels in the image
' ****************************************************************************
'
'' Create a new bitmap.
'Dim bmp As Bitmap = Bitmap.FromFile("C:\DesktopScreenshot.bmp", False)
'
'' Instance a PixelUtil Class.
'Dim bmpPixelUtil As New PixelUtil(bmp)
'
'' Specify the pixel range to retrieve.
'Dim RangeMin As Integer = 1919I
'Dim RangeMax As Integer = 1921I
'
'' Get the pixel data.
'Dim FoundPixels As List(Of PixelUtil.PixelData) = bmpPixelUtil.GetPixelData(RangeMin, RangeMax)
'
'' Loop through each pixel.
'For Each Pixel As PixelUtil.PixelData In FoundPixels
'
'    Dim sb As New System.Text.StringBuilder
'    With sb
'
'        .AppendLine(String.Format("Index: {0}", CStr(Pixel.Index)))
'        .AppendLine(String.Format("Color: {0}", Pixel.Color.ToString))
'        .AppendLine(String.Format("Coord: {0}", Pixel.Coordinates.ToString))
'
'        MessageBox.Show(.ToString, "Pixel-Color Search")
'
'        .Clear()
'
'    End With
'
'Next Pixel


#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices

#End Region

#Region " PixelUtil "

Public Class PixelUtil

#Region " Vars, Properties "

   Private _PixelData As List(Of PixelData) = Nothing
   Private _bmp As Bitmap = Nothing
   Private _PixelCount As Integer = Nothing

   ''' <summary>
   ''' Gets the Bitmap object.
   ''' </summary>
   ''' <value>The BMP.</value>
   Public ReadOnly Property bmp As Bitmap
       Get
           Return Me._bmp
       End Get
   End Property

   ''' <summary>
   ''' Gets the total amount of pixels that contains the Bitmap.
   ''' </summary>
   ''' <value>The pixel count.</value>
   Public ReadOnly Property PixelCount As Integer
       Get
           Return Me._PixelCount
       End Get
   End Property

#End Region

#Region " Classes "

   ''' <summary>
   ''' Stores specific pixel information of an image.
   ''' </summary>
   Public Class PixelData

       ''' <summary>
       ''' Gets or sets the pixel index.
       ''' </summary>
       ''' <value>The pixel index.</value>
       Public Property Index As Integer

       ''' <summary>
       ''' Gets or sets the pixel color.
       ''' </summary>
       ''' <value>The pixel color.</value>
       Public Property Color As Color

       ''' <summary>
       ''' Gets or sets the pixel coordinates relative to the image.
       ''' </summary>
       ''' <value>The pixel coordinates.</value>
       Public Property Coordinates As Point

   End Class

#End Region

#Region " Constructors "

   ''' <summary>
   ''' Prevents a default instance of the <see cref="PixelUtil"/> class from being created.
   ''' </summary>
   Private Sub New()
   End Sub

   ''' <summary>
   ''' Initializes a new instance of the <see cref="PixelUtil"/> class.
   ''' </summary>
   ''' <param name="bmp">Indicates the Bitmap image to process it's pixels.</param>
   ''' <exception cref="System.Exception">PixelFormat unsupported.</exception>
   Public Sub New(ByVal bmp As Bitmap)

       If Not bmp.PixelFormat = PixelFormat.Format24bppRgb Then
           Throw New Exception("PixelFormat unsupported.")
       End If

       Me._bmp = bmp
       Me._PixelCount = Me.[Count]

   End Sub

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Returns a <c>'PixelData'</c> object containing information about each pixel in the image.
   ''' </summary>
   ''' <returns>List(Of PixelData).</returns>
   Public Function GetPixelData() As List(Of PixelData)

       If Me._PixelData Is Nothing Then

           Me._PixelData = New List(Of PixelData)

           ' Lock the Bitmap bits.
           Dim bmpRect As New Rectangle(0, 0, Me._bmp.Width, Me._bmp.Height)
           Dim bmpData As BitmapData = Me._bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, Me._bmp.PixelFormat)

           ' Get the address of the first line.
           Dim Pointer As IntPtr = bmpData.Scan0

           ' Hold the bytes of the bitmap into a Byte-Array.
           ' NOTE: This code is specific to a bitmap with 24 bits per pixels.
           Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height)
           Dim rgbData(bmpBytes - 1) As Byte

           ' Copy the RGB values into the array.
           Marshal.Copy(Pointer, rgbData, 0, bmpBytes)

           ' Unlock the Bitmap bits.
           Me._bmp.UnlockBits(bmpData)

           ' Loop through each 24bpp-RGB value.
           For rgbIndex As Integer = 2 To rgbData.Length - 1 Step 3

               ' Set the pixel Data.
               Dim Pixel As New PixelData

               With Pixel

                   .Index = rgbIndex \ 3I

                   .Color = Color.FromArgb(red:=rgbData(rgbIndex),
                                           green:=rgbData(rgbIndex - 1I),
                                           blue:=rgbData(rgbIndex - 2I))

                   .Coordinates = New Point(X:=(.Index Mod bmpRect.Width),
                                            Y:=(.Index - (.Index Mod bmpRect.Width)) \ bmpRect.Width)

               End With

               ' Add the PixelData into the list.
               Me._PixelData.Add(Pixel)

           Next rgbIndex

       End If

       Return Me._PixelData

   End Function

   ''' <summary>
   ''' Returns a <c>'PixelData'</c> object containing information about a range of pixels in the image.
   ''' </summary>
   ''' <returns>List(Of PixelData).</returns>
   ''' <exception cref="System.Exception">Pixel index is out of range</exception>
   Public Function GetPixelData(ByVal RangeMin As Integer,
                                ByVal RangeMax As Integer) As List(Of PixelData)

       If Not (Me._PixelCount >= RangeMin AndAlso Me._PixelCount <= RangeMax) Then
           Throw New Exception("Pixel index is out of range.")
           Return Nothing
       End If

       ' Return the Pixel range.
       Return (From Pixel As PixelData In Me.GetPixelData()
               Where (Pixel.Index >= RangeMin AndAlso Pixel.Index <= RangeMax)).ToList

   End Function

   ''' <summary>
   ''' Searchs for the specified pixel-color inside the image and returns all the matches.
   ''' </summary>
   ''' <param name="PixelColor">Indicates the color to find.</param>
   ''' <returns>List(Of PixelData).</returns>
   Public Function SearchColor(ByVal PixelColor As Color) As List(Of PixelData)

       Return (From Pixel As PixelData In Me.GetPixelData
               Where Pixel.Color = PixelColor).ToList

   End Function

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Counts the number of pixels that contains the image.
   ''' </summary>
   ''' <returns>The number of pixels.</returns>
   Private Function [Count]() As Integer

       ' Lock the Bitmap bits.
       Dim bmpRect As New Rectangle(0, 0, Me._bmp.Width, Me._bmp.Height)
       Dim bmpData As BitmapData = Me._bmp.LockBits(bmpRect, ImageLockMode.ReadWrite, Me._bmp.PixelFormat)

       ' Get the address of the first line.
       Dim Pointer As IntPtr = bmpData.Scan0

       ' Hold the bytes of the bitmap into a Byte-Array.
       ' NOTE: This code is specific to a bitmap with 24 bits per pixels.
       Dim bmpBytes As Integer = (Math.Abs(bmpData.Stride) * bmpRect.Height)
       Dim rgbData(bmpBytes - 1) As Byte

       ' Copy the RGB values into the array.
       Marshal.Copy(Pointer, rgbData, 0, bmpBytes)

       ' Unlock the Bitmap bits.
       Me._bmp.UnlockBits(bmpData)

       Return rgbData.Count

   End Function

#End Region

#Region " Hidden Methods "

   ''' <summary>
   ''' Serves as a hash function for a particular type.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Sub GetHashCode()
   End Sub

   ''' <summary>
   ''' Determines whether the specified System.Object is equal to the current System.Object.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Sub Equals()
   End Sub

   ''' <summary>
   ''' Returns a String that represents the current object.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Sub ToString()
   End Sub

#End Region

End Class

#End Region

#6734
¿Que es lo que no entiendes exactamente, la visibilidad del miembro, lo que es una constante, el datatype 'int', el valor hexadecimal, o lo que?
Deberías leer un manual básico de C#.

Como ya viste, el primer parámetro (dwFlags) de la función "mouse_event" acepta muchos valores: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646260%28v=vs.85%29.aspx

A cada valor se le suele asignar un nombre (en este caso "MOUSEEVENTF_LEFTDOWN") ya sea usando constantes o una Enum o como se prefiera, para que sea más facil de manejar y sobretodo de recordar.

El "0x0002" es el valor en hexadecimal, en decimal es "2".

Saludos...
#6735
Te dejo aquí un regalito, esto lo escribí hoy, es la base con todos los métodos que puedas llegar a necesitar (añadir un mapeo, eliminarlo, desactivarlo, etc...),
la creación y el diseño de la interfaz gráfica sería cosa tuya, solo tendrías que instanciar esta Class y hacer que los elementos de la interfaz interactuasen con los métodos de éste.

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 08-11-2014
' ***********************************************************************
' <copyright file="HostsFile.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

'Public Class HostsFileTestClass
'
'    Private Sub HostsFileTestHandler() Handles MyBase.Shown
'
'        ' Instance the HostsFile Class.
'        Dim Hosts As New HostsFile()
'
'        ' Set a new mapping.
'        Dim Mapping As New HostsFile.MappingInfo
'        With Mapping
'            .HostName = "cuantodanio.es"
'            .IP = Hosts.LOCALHOST ' "127.0.0.1"
'            .Comment = "Test mapping comment."
'        End With
'
'        With Hosts
'
'            ' Delete the Host file.
'            If .FileExists Then
'                .FileDelete()
'            End If
'
'            ' Create a new one Hosts file.
'            .FileCreate()
'
'            ' Add some new mappings.
'            .Add(Mapping)
'            .Add(HostName:="www.youtube.com", IP:=.LOCALHOST, Comment:="Test mapping comment")
'
'            ' Check if a mapping exists.
'            If .IsMapped(Mapping) Then
'                ' Disable the mapping.
'                .Disable(Mapping)
'            End If
'
'            ' Check if an existint mapping is disabled.
'            If .IsDisabled("www.youtube.com") Then
'                ' Remove the mapping.
'                .Remove("www.youtube.com")
'            End If
'
'            ' Open the HOSTS file with the specified text-editor.
'            .FileOpen("C:\Program Files\Sublime Text\sublime_text.exe")
'
'        End With
'
'        ' Get the IP of a mapped Hostname.
'        MessageBox.Show("cuantodanio.es: " & Hosts.GetMappingFromHostname("cuantodanio.es").IP)
'
'        ' Get all the hostname mappings
'        Dim Mappings As List(Of HostsFile.MappingInfo) = Hosts.GetMappings()
'        For Each MappingInfo As HostsFile.MappingInfo In Mappings
'
'            Dim sb As New System.Text.StringBuilder
'            With sb
'                .AppendLine(String.Format("Hostname...: {0}", MappingInfo.HostName))
'                .AppendLine(String.Format("IP Address.: {0}", MappingInfo.IP))
'                .AppendLine(String.Format("Comment....: {0}", MappingInfo.Comment))
'                .AppendLine(String.Format("Is Enabled?: {0}", Not MappingInfo.IsDisabled))
'            End With
'
'            MessageBox.Show(sb.ToString, "HostsFile Mappings", MessageBoxButtons.OK, MessageBoxIcon.Information)
'
'        Next MappingInfo
'
'        ' Get all the hostname mappings that matches an ip address
'        Dim MappingMatches As List(Of HostsFile.MappingInfo) = Hosts.GetMappingsFromIP(Hosts.LOCALHOST)
'
'    End Sub
'
'End Class

#End Region

#Region " Imports "

Imports System.IO
Imports System.Net
Imports System.Text
'Imports System.Text.RegularExpressions

#End Region

#Region " Hosts File "

''' <summary>
''' Manages the Windows HOSTS file to map Hostnames to IP addresses.
''' </summary>
Public Class HostsFile

#Region " Constructors "

   ''' <summary>
   ''' Initializes a new instance of the <see cref="HostsFile"/> class.
   ''' </summary>
   ''' <param name="HOSTSLocation">
   ''' Optionaly indicates a custom Hosts file location.
   ''' Default value is 'X:\Windows\System32\Drivers\etc\hosts'.
   ''' </param>
   Public Sub New(Optional ByVal HOSTSLocation As String = Nothing)

       If Not String.IsNullOrEmpty(HOSTSLocation) Then
           Me._HOSTSLocation = HOSTSLocation
       End If

   End Sub

   ''' <summary>
   ''' Prevents a default instance of the <see cref="HostsFile"/> class from being created.
   ''' </summary>
   Private Sub New()
   End Sub

#End Region

#Region " Properties "

   ''' <summary>
   ''' The Hosts file location.
   ''' </summary>
   ''' <value>The Hosts file location.</value>
   Public ReadOnly Property HOSTSLocation As String
       Get
           Return _HOSTSLocation
       End Get
   End Property
   Private SysDir As String = Environment.GetFolderPath(Environment.SpecialFolder.System)
   Private _HOSTSLocation As String = Path.Combine(SysDir, "Drivers\etc\hosts")

   ''' <summary>
   ''' The Hosts file encoding.
   ''' The encoding must be <see cref="Encoding.Default"/> (ANSI) or <see cref="Encoding.UTF8"/> (UTF-8 without BOM),
   ''' otherwise the entries will be ignored by Windows.
   ''' </summary>
   ''' <value>The Hosts file encoding.</value>
   Public Property HOSTSEncoding As Encoding
       Get
           Return _HOSTSEncoding
       End Get
       Set(ByVal value As Encoding)
           Me._HOSTSEncoding = value
       End Set
   End Property
   Private _HOSTSEncoding As Encoding = Encoding.Default

   ''' <summary>
   ''' Gets or sets the default 'LocalHost' IP address.
   ''' In most computers the default address is '127.0.0.1'.
   ''' </summary>
   ''' <value>The default LocalHost.</value>
   Public Property LOCALHOST As String
       Get
           Return Me._LOCALHOST
       End Get
       Set(ByVal value As String)
           Me._LOCALHOST = value
       End Set
   End Property
   Private _LOCALHOST As String = "127.0.0.1"

   ''' <summary>
   ''' Gets the default Hosts file header.
   ''' </summary>
   Private ReadOnly HostsHeader As String =
<a><![CDATA[
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
]]></a>.Value

#End Region

#Region " Types "

#Region " MappingInfo "

   ''' <summary>
   ''' Specifies info of a HOSTS file mapping.
   ''' </summary>
   Public Class MappingInfo

       ''' <summary>
       ''' Gets or sets the hostname.
       ''' </summary>
       ''' <value>The hostname.</value>
       Public Property HostName As String

       ''' <summary>
       ''' Gets or sets the IP address.
       ''' </summary>
       ''' <value>The IP address.</value>
       Public Property IP As String

       ''' <summary>
       ''' Gets or sets the mapping comment.
       ''' </summary>
       ''' <value>The mapping comment.</value>
       Public Property Comment As String

       ''' <summary>
       ''' This value is reserved.
       ''' Gets a value indicating whether the mapping is disabled in the HOSTS file.
       ''' </summary>
       ''' <value><c>true</c> if the mapping is disabled, <c>false</c> otherwise.</value>
       Public Property IsDisabled As Boolean

   End Class

#End Region

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Adds a new mapping.
   ''' </summary>
   ''' <param name="HostName">Indicates the Hostname.</param>
   ''' <param name="IP">Indicates the IP address.</param>
   ''' <param name="Comment">Indicates a comment for this mapping.</param>
   ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
   ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
   ''' <exception cref="System.Exception">Hostname is already mapped.</exception>
   Public Sub Add(ByVal HostName As String,
                  ByVal IP As String,
                  Optional ByVal Comment As String = Nothing)

       If Not Me.FileExists() Then ' Hosts file does not exists.
           Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

       ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
           Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))

       ElseIf Me.IsMapped(HostName) Then ' Hostname is already mapped.
           Throw New Exception(String.Format("Hostname '{0}' is already mapped.", HostName))

       Else ' Add the entry.

           ' Fix value spacing.
           Dim EntryFormat As String =
               IP & HostName.Insert(0I, ControlChars.Tab) &
               If(Not String.IsNullOrEmpty(Comment),
                  Comment.Insert(0I, ControlChars.Tab & "#"c),
                  String.Empty)

           ' Write the mapping.
           File.AppendAllText(Me._HOSTSLocation, Environment.NewLine & EntryFormat, Me._HOSTSEncoding)

       End If

   End Sub

   ''' <summary>
   ''' Adds a new mapping.
   ''' </summary>
   ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
   Public Sub Add(ByVal MappingInfo As MappingInfo)

       Me.Add(MappingInfo.HostName, MappingInfo.IP, MappingInfo.Comment)

   End Sub

   ''' <summary>
   ''' Disables an existing mapping.
   ''' </summary>
   ''' <param name="HostName">Indicates the Hostname.</param>
   ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
   ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
   ''' <exception cref="System.Exception">Hostname is already disabled.</exception>
   Public Sub Disable(ByVal HostName As String)

       If Not Me.FileExists() Then ' Hosts file does not exists.
           Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

       ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
           Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))

       ElseIf Me.IsDisabled(HostName) Then ' Hostname is already disabled.
           Throw New Exception(String.Format("Hostname: '{0}' is already disabled.", HostName))

       Else ' Disable the mapping.

           ' Retrieve the HOSTS file content.
           Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList

           ' Iterate the mappings.
           For X As Integer = 0I To (Hosts.Count - 1I)

               If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                   ' Retrieve the HostName of this mapping.
                   Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                   If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then

                       ' Disable the mapping.
                       Hosts(X) = Hosts(X).Insert(0I, "#"c)
                       Exit For

                   End If ' Host.Equals(...)

               End If ' Not String.IsNullOrEmpty(Hosts(X))...

           Next X

           File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)

       End If

   End Sub

   ''' <summary>
   ''' Disables an existing mapping.
   ''' </summary>
   ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
   Public Sub Disable(ByVal MappingInfo As MappingInfo)

       Me.Disable(MappingInfo.HostName)

   End Sub

   ''' <summary>
   ''' Removes a mapping.
   ''' </summary>
   ''' <param name="HostName">Indicates the Hostname.</param>
   ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
   ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
   Public Sub Remove(ByVal HostName As String)

       If Not Me.FileExists() Then ' Hosts file does not exists.
           Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

       ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
           Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))

       Else ' Remove the mapping.

           ' Retrieve the HOSTS file content.
           Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList

           ' Iterate the mappings.
           For X As Integer = 0I To (Hosts.Count - 1I)

               If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                   ' Retrieve the HostName of this mapping.
                   Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                   If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then

                       ' Remove the mapping.
                       Hosts.RemoveAt(X)
                       Exit For

                   End If ' Host.Equals(...)

               End If ' Not String.IsNullOrEmpty(Hosts(X))...

           Next X

           File.WriteAllLines(Me._HOSTSLocation, Hosts, Me._HOSTSEncoding)

       End If

   End Sub

   ''' <summary>
   ''' Removes a mapping.
   ''' </summary>
   ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
   Public Sub Remove(ByVal MappingInfo As MappingInfo)

       Me.Remove(MappingInfo.HostName)

   End Sub

   ''' <summary>
   ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings.
   ''' </summary>
   ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
   Public Function GetMappings() As List(Of MappingInfo)

       If Not Me.FileExists() Then ' Hosts file does not exists.
           Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

       Else ' Get the mapping.

           ' Retrieve the HOSTS file content.
           Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
           Dim Mappings As New List(Of MappingInfo)

           ' Iterate the mappings.
           For X As Integer = 0I To (Hosts.Count - 1I)

               If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                   ' Retrieve the mapping parts.
                   Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})

                   Dim MappingInfo As New MappingInfo
                   With MappingInfo
                       .HostName = Parts(1I)
                       .IP = Parts(0I).Replace("#"c, String.Empty)
                       .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
                       .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
                   End With ' MappingInfo

                   Mappings.Add(MappingInfo)

               End If ' Not String.IsNullOrEmpty(Hosts(X))...

           Next X

           Return Mappings

       End If

   End Function

   ''' <summary>
   ''' Gets a <see cref="MappingInfo"/> instance containing the mapping info of a Hostname.
   ''' </summary>
   ''' <param name="HostName">Indicates the Hostname.</param>
   ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
   ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
   Public Function GetMappingFromHostname(ByVal Hostname As String) As MappingInfo

       If Not Me.FileExists() Then ' Hosts file does not exists.
           Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

       ElseIf Not Me.IsMapped(Hostname) Then ' Hostname is not mapped.
           Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", Hostname))

       Else ' Get the mapping.

           ' Retrieve the HOSTS file content.
           Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
           Dim MappingInfo As New MappingInfo

           ' Iterate the mappings.
           For X As Integer = 0I To (Hosts.Count - 1I)

               If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                   ' Retrieve the mapping parts.
                   Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})

                   If Parts(1I).Equals(Hostname, StringComparison.OrdinalIgnoreCase) Then

                       With MappingInfo
                           .HostName = Parts(1I)
                           .IP = Parts(0I).Replace("#"c, String.Empty)
                           .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
                           .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
                       End With ' MappingInfo

                       Exit For

                   End If ' Parts(1I).Equals(Hostname)...

               End If ' Not String.IsNullOrEmpty(Hosts(X))...

           Next X

           Return MappingInfo

       End If

   End Function

   ''' <summary>
   ''' Gets a <see cref="List(Of HostsMapping)"/> instance containing the mapping info of all mappings
   ''' matching the specified IP address.
   ''' </summary>
   ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
   ''' <exception cref="System.FormatException">Invalid IP adress.</exception>
   Public Function GetMappingsFromIP(ByVal IP As String) As List(Of MappingInfo)

       If Not Me.FileExists() Then ' Hosts file does not exists.
           Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

       ElseIf Not Me.ValidateIP(IP) Then ' Invalid IP address.
           Throw New FormatException(String.Format("Address: '{0}' is not a valid IP adress.", IP))

       Else ' Get the mapping.

           ' Retrieve the HOSTS file content.
           Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
           Dim Mappings As New List(Of MappingInfo)

           ' Iterate the mappings.
           For X As Integer = 0I To (Hosts.Count - 1I)

               If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                   ' Retrieve the mapping parts.
                   Dim Parts As String() = Hosts(X).Split({ControlChars.Tab})

                   If Parts(0I).Replace("#"c, String.Empty).Equals(IP) Then

                       Dim MappingInfo As New MappingInfo
                       With MappingInfo
                           .HostName = Parts(1I)
                           .IP = Parts(0I).Replace("#"c, String.Empty)
                           .Comment = If(Parts.Count > 1I, Parts(2I), String.Empty)
                           .IsDisabled = Parts(0I).TrimStart.StartsWith("#"c)
                       End With ' MappingInfo

                       Mappings.Add(MappingInfo)

                   End If

               End If ' Not String.IsNullOrEmpty(Hosts(X))...

           Next X

           Return Mappings

       End If

   End Function

   ''' <summary>
   ''' Checks whether a HostName is already mapped.
   ''' </summary>
   ''' <param name="HostName">Indicates the Hostname.</param>
   ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
   ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
   Public Function IsMapped(ByVal HostName As String) As Boolean

       If Not Me.FileExists() Then ' Hosts file does not exists.
           Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

       Else
           ' Retrieve the HOSTS file content.
           Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList

           ' Iterate the mappings.
           For X As Integer = 0I To (Hosts.Count - 1I)

               If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                   ' Retrieve the HostName of this mapping.
                   Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                   If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
                       Return True
                   End If ' Host.Equals(HostName)...

               End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...

           Next X

           Return False

       End If ' Not Me.Exists()...

   End Function

   ''' <summary>
   ''' Checks whether a HostName is already mapped.
   ''' </summary>
   ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
   ''' <returns><c>true</c> if the specified Hostname is mapped; otherwise, <c>false</c>.</returns>
   Public Function IsMapped(ByVal MappingInfo As MappingInfo) As Boolean

       Return Me.IsMapped(MappingInfo.HostName)

   End Function

   ''' <summary>
   ''' Checks whether a HostName is already disabled.
   ''' </summary>
   ''' <param name="HostName">Indicates the Hostname.</param>
   ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
   ''' <exception cref="System.IO.FileNotFoundException">"Hosts file not found."</exception>
   ''' <exception cref="System.Exception">Hostname is not mapped.</exception>
   Public Function IsDisabled(ByVal HostName As String) As Boolean

       If Not Me.FileExists() Then ' Hosts file does not exists.
           Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

       ElseIf Not Me.IsMapped(HostName) Then ' Hostname is not mapped.
           Throw New Exception(String.Format("Hostname: '{0}' is not mapped.", HostName))

       Else
           ' Retrieve the HOSTS file content.
           Dim Hosts As List(Of String) = File.ReadAllLines(Me._HOSTSLocation, Me._HOSTSEncoding).ToList
           Dim Result As Boolean = False

           ' Iterate the mappings.
           For X As Integer = 0I To (Hosts.Count - 1I)

               If Not String.IsNullOrEmpty(Hosts(X)) AndAlso Hosts(X).Contains(ControlChars.Tab) Then

                   ' Retrieve the HostName of this mapping.
                   Dim Host As String = Hosts(X).Split({ControlChars.Tab})(1I)

                   If Host.Equals(HostName, StringComparison.OrdinalIgnoreCase) Then
                       Result = Hosts(X).TrimStart.StartsWith("#"c)
                       Exit For
                   End If ' Host.Equals(HostName)...

               End If ' Not String.IsNullOrEmpty(Hosts(X)) AndAlso...

           Next X

           Return Result

       End If

   End Function

   ''' <summary>
   ''' Checks whether a HostName is already disabled.
   ''' </summary>
   ''' <param name="MappingInfo">A <see cref="MappingInfo"/> instance containing the mapping info.</param>
   ''' <returns><c>true</c> if the specified Hostname is disabled; otherwise, <c>false</c>.</returns>
   Public Function IsDisabled(ByVal MappingInfo As MappingInfo) As Boolean

       Return Me.IsDisabled(MappingInfo.HostName)

   End Function

   ''' <summary>
   ''' Checks whether the Hosts file exists.
   ''' </summary>
   ''' <returns><c>true</c> if Hosts file exists, <c>false</c> otherwise.</returns>
   Public Function FileExists() As Boolean

       Return File.Exists(Me._HOSTSLocation)

   End Function

   ''' <summary>
   ''' Creates the Hosts file.
   ''' </summary>
   Public Sub FileCreate()

       If Me.FileExists() Then
           File.Delete(Me._HOSTSLocation)
       End If

       File.WriteAllText(Me._HOSTSLocation, Me.HostsHeader, Me._HOSTSEncoding)

   End Sub

   ''' <summary>
   ''' Deletes the Hosts file.
   ''' </summary>
   ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
   Public Sub FileDelete()

       If Not Me.FileExists() Then
           Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

       Else
           File.Delete(Me._HOSTSLocation)

       End If

   End Sub

   ''' <summary>
   ''' Cleans the Hosts file.
   ''' This removes all the mappings and adds the default file header.
   ''' </summary>
   Public Sub FileClean()

       Me.FileCreate()

   End Sub

   ''' <summary>
   ''' Opens the Hosts file with the specified process.
   ''' </summary>
   ''' <param name="Process">
   ''' Indicates the process location.
   ''' Default value is: "notepad.exe".
   ''' </param>
   ''' <exception cref="System.IO.FileNotFoundException">Hosts file not found.</exception>
   ''' <exception cref="System.IO.FileNotFoundException">Process not found.</exception>
   Public Sub FileOpen(Optional ByVal Process As String = "notepad.exe")

       If Not Me.FileExists Then
           Throw New FileNotFoundException("Hosts file not found.", Me._HOSTSLocation)

       ElseIf Not File.Exists(Process) Then
           Throw New FileNotFoundException("Process not found.", Process)

       Else
           Diagnostics.Process.Start(Process, ControlChars.Quote & Me._HOSTSLocation & ControlChars.Quote)

       End If

   End Sub

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Validates an IP address.
   ''' </summary>
   ''' <param name="Address">The IP address.</param>
   ''' <returns><c>true</c> if IP is in the proper format, <c>false</c> otherwise.</returns>
   Private Function ValidateIP(ByVal Address As String) As Boolean

       Dim IP As IPAddress = Nothing
       Return IPAddress.TryParse(Address, IP)

   End Function

#End Region

End Class

#End Region


Ejemplos de uso:

Código (vbnet) [Seleccionar]
Public Class HostsFileTestClass

   Private Sub HostsFileTestHandler() Handles MyBase.Shown

       ' Instance the HostsFile Class.
       Dim Hosts As New HostsFile()

       ' Set a new mapping.
       Dim Mapping As New HostsFile.MappingInfo
       With Mapping
           .HostName = "cuantodanio.es"
           .IP = Hosts.LOCALHOST ' "127.0.0.1"
           .Comment = "Test mapping comment."
       End With

       With Hosts

           ' Delete the Host file.
           If .FileExists Then
               .FileDelete()
           End If

           ' Create a new one Hosts file.
           .FileCreate()

           ' Add some new mappings.
           .Add(Mapping)
           .Add(HostName:="www.youtube.com", IP:=.LOCALHOST, Comment:="Test mapping comment")

           ' Check if a mapping exists.
           If .IsMapped(Mapping) Then
               ' Disable the mapping.
               .Disable(Mapping)
           End If

           ' Check if an existint mapping is disabled.
           If .IsDisabled("www.youtube.com") Then
               ' Remove the mapping.
               .Remove("www.youtube.com")
           End If

           ' Open the HOSTS file with the specified text-editor.
           .FileOpen("C:\Program Files\Sublime Text\sublime_text.exe")

       End With

       ' Get the IP of a mapped Hostname.
       MessageBox.Show("cuantodanio.es: " & Hosts.GetMappingFromHostname("cuantodanio.es").IP)

       ' Get all the hostname mappings
       Dim Mappings As List(Of HostsFile.MappingInfo) = Hosts.GetMappings()
       For Each MappingInfo As HostsFile.MappingInfo In Mappings

           Dim sb As New System.Text.StringBuilder
           With sb
               .AppendLine(String.Format("Hostname...: {0}", MappingInfo.HostName))
               .AppendLine(String.Format("IP Address.: {0}", MappingInfo.IP))
               .AppendLine(String.Format("Comment....: {0}", MappingInfo.Comment))
               .AppendLine(String.Format("Is Enabled?: {0}", Not MappingInfo.IsDisabled))
           End With

           MessageBox.Show(sb.ToString, "HostsFile Mappings", MessageBoxButtons.OK, MessageBoxIcon.Information)

       Next MappingInfo

       ' Get all the hostname mappings that matches an ip address
       Dim MappingMatches As List(Of HostsFile.MappingInfo) = Hosts.GetMappingsFromIP(Hosts.LOCALHOST)

   End Sub

End Class
#6736
Cita de: andrecid en 10 Agosto 2014, 18:55 PMNo se si me entienden.

Sinceramente, yo no lo entendí xD. ¿la risa es un Audio, un modelo 3D, una imagen GIF?

Tengo entendido que .NET no es viable para el desarrollo de juegos 3D (saldrían cosas mediocres), no se sobre ese tema, me gustaría leer una respuesta del compañero @Kubox, recuerdo que me enseñó un juego de naves que hizo xD y parece estar familiarizado con ese tema.

Eso sí, es indispensable que te mires y aprendas todo lo que puedas acerca de GDI/GDI+, es la base para manipular gráficos en .NET.

· Windows GDI
· GDI+ Graphics
· GDI+ Reference

Saludos
#6737
Estás haciendo una llamada al método "mouse_event", posiblemente sacado de la WinAPI: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646260%28v=vs.85%29.aspx
Ahí tienes toda la documentación necesaria.




En el primer parámetro (dwFlags) le estás indicando la accion a realizar (el código que muestras mantiene el botón izquierdo apretado, y luego lo suelta)

El segundo y el tercer parámetro (dx , dy) son para indicar las coordenadas (X, Y)

El cuarto parámetro (dwData ) es bastante abstracto, si indicas en el primer parámetro (dwFlags) la acción de mover la rueda del ratón entonces este parámetro servirá para indicar las veces que se ha de simular el giro de ruedas del mouse. también sirve para especificar más cosas en otras acciones.

El último parámetro (dwExtraInfo) es innecesario usarlo practicamente en la gran mayoría de los casos y no me queda muy clara su función, sirve para especificar un valor adicional asociado con el evento (no el 'mouse_event', sinó el evento del mouse, la acción del primer parámetro) y se ha de utilizar la función 'GetMessageExtraInfo' (de la WinAPI) para obtener la información de ese puntero.

Nota: El método 'mouse_event' está obsoleto y en su defecto se recomienda usar 'SendInputs'.

Saludos.
#6738
Como partir un archivo en pequeños trozos de cualuier tamaño (no hay limite de 2 GB).

Código (vbnet) [Seleccionar]
    ' Split File
    ' By Elektro
    '
    ' Example Usage:
    ' SplitFile(InputFile:="C:\Test.mp3", ChunkSize:=(1024L ^ 2L), ChunkName:="Test.Part", ChunkExt:="mp3", Overwrite:=True)

    ''' <summary>
    ''' Splits a file into chunks.
    ''' </summary>
    ''' <param name="InputFile">
    ''' Indicates the input file to split.
    ''' </param>
    ''' <param name="ChunkSize">
    ''' Indicates the size of each chunk.
    ''' </param>
    ''' <param name="ChunkName">
    ''' Indicates the chunk filename format.
    ''' Default format is: 'FileName.ChunkIndex.FileExt'
    ''' </param>
    ''' <param name="ChunkExt">
    ''' Indicates the chunk file-extension.
    ''' If this value is <c>Null</c>, the input file-extension will be used.
    ''' </param>
    ''' <param name="Overwrite">
    ''' If set to <c>true</c>, chunk files will replace any existing file;
    ''' Otherwise, an exception will be thrown.
    ''' </param>
    ''' <exception cref="System.OverflowException">'ChunkSize' should be smaller than the Filesize.</exception>
    ''' <exception cref="System.IO.IOException"></exception>
    Public Sub SplitFile(ByVal InputFile As String,
                         ByVal ChunkSize As Long,
                         Optional ByVal ChunkName As String = Nothing,
                         Optional ByVal ChunkExt As String = Nothing,
                         Optional ByVal Overwrite As Boolean = False)

        ' FileInfo instance of the input file.
        Dim fInfo As New IO.FileInfo(InputFile)

        ' The buffer to read data and write the chunks.
        Dim Buffer As Byte() = New Byte() {}

        ' The buffer length.
        Dim BufferSize As Integer = 1048576 ' 1048576 = 1 mb | 33554432 = 32 mb | 67108864 = 64 mb

        ' Counts the length of the current chunk file.
        Dim BytesWritten As Long = 0L

        ' The total amount of chunks to create.
        Dim ChunkCount As Integer = CInt(Math.Floor(fInfo.Length / ChunkSize))

        ' Keeps track of the current chunk.
        Dim ChunkIndex As Integer = 0I

        ' A zero-filled string to enumerate the chunk files.
        Dim Zeros As String = String.Empty

        ' The given filename for each chunk.
        Dim ChunkFile As String = String.Empty

        ' The chunk file basename.
        ChunkName = If(String.IsNullOrEmpty(ChunkName),
                       IO.Path.Combine(fInfo.DirectoryName, IO.Path.GetFileNameWithoutExtension(fInfo.Name)),
                       IO.Path.Combine(fInfo.DirectoryName, ChunkName))

        ' The chunk file extension.
        ChunkExt = If(String.IsNullOrEmpty(ChunkExt),
                      fInfo.Extension.Substring(1I),
                      ChunkExt)

        ' If ChunkSize is bigger than filesize then...
        If ChunkSize >= fInfo.Length Then
            Throw New OverflowException("'ChunkSize' should be smaller than the Filesize.")
            Exit Sub

            ' For cases where a chunksize is smaller than the buffersize.
        ElseIf ChunkSize < BufferSize Then
            BufferSize = CInt(ChunkSize)

        End If ' ChunkSize <>...

        ' If not file-overwritting is allowed then...
        If Not Overwrite Then

            For Index As Integer = 0I To (ChunkCount)

                ' Set chunk filename.
                Zeros = New String("0", CStr(ChunkCount).Length - CStr(Index + 1I).Length)
                ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(Index + 1I), ChunkExt)

                ' If chunk file already exists then...
                If IO.File.Exists(ChunkFile) Then

                    Throw New IO.IOException(String.Format("File already exist: {0}", ChunkFile))
                    Exit Sub

                End If ' IO.File.Exists(ChunkFile)

            Next Index

            Zeros = String.Empty
            ChunkFile = String.Empty

        End If ' Overwrite

        ' Open the file to start reading bytes.
        Using InputStream As New IO.FileStream(fInfo.FullName, IO.FileMode.Open)

            Using BinaryReader As New IO.BinaryReader(InputStream)

                While (InputStream.Position < InputStream.Length)

                    ' Set chunk filename.
                    Zeros = New String("0", CStr(ChunkCount).Length - CStr(ChunkIndex + 1I).Length)
                    ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(ChunkIndex + 1I), ChunkExt)

                    ' Reset written byte-length counter.
                    BytesWritten = 0L

                    ' Create the chunk file to Write the bytes.
                    Using OutputStream As New IO.FileStream(ChunkFile, IO.FileMode.Create)

                        Using BinaryWriter As New IO.BinaryWriter(OutputStream)

                            ' Read until reached the end-bytes of the input file.
                            While (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)

                                ' Read bytes from the original file (BufferSize byte-length).
                                Buffer = BinaryReader.ReadBytes(BufferSize)

                                ' Write those bytes in the chunk file.
                                BinaryWriter.Write(Buffer)

                                ' Increment the size counter.
                                BytesWritten += Buffer.Count

                            End While ' (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)

                            OutputStream.Flush()

                        End Using ' BinaryWriter

                    End Using ' OutputStream

                    ChunkIndex += 1I 'Increment file counter

                End While ' InputStream.Position < InputStream.Length

            End Using ' BinaryReader

        End Using ' InputStream

    End Sub
#6739
.NET (C#, VB.NET, ASP) / Re: Partir archivo
10 Agosto 2014, 13:36 PM
Cita de: Meta en 10 Agosto 2014, 04:27 AM¿Cómo se hace?

¿Que has intentado?, ¿donde está tu código?, aquí no hacemos el trabajo a nadie, ayudamos a que lo puedas hacer por ti mismo.

Tienes todo tipo de ejemplos en Google: http://www.codeproject.com/Articles/2737/File-Split-Merge-Tool

De todas formas, la idea me pareció interesante, aquí va mi enfoque:

Cita de: http://foro.elhacker.net/net/libreria_de_snippets_compartan_aqui_sus_snippets-t378770.0.html;msg1959642#msg1959642
Código (vbnet) [Seleccionar]
   ' Split File
   ' By Elektro
   '
   ' Example Usage:
   ' SplitFile(InputFile:="C:\Test.mp3", ChunkSize:=(1024L ^ 2L), ChunkName:="Test.Part", ChunkExt:="mp3", Overwrite:=True)

   ''' <summary>
   ''' Splits a file into chunks.
   ''' </summary>
   ''' <param name="InputFile">
   ''' Indicates the input file to split.
   ''' </param>
   ''' <param name="ChunkSize">
   ''' Indicates the size of each chunk.
   ''' </param>
   ''' <param name="ChunkName">
   ''' Indicates the chunk filename format.
   ''' Default format is: 'FileName.ChunkIndex.FileExt'
   ''' </param>
   ''' <param name="ChunkExt">
   ''' Indicates the chunk file-extension.
   ''' If this value is <c>Null</c>, the input file-extension will be used.
   ''' </param>
   ''' <param name="Overwrite">
   ''' If set to <c>true</c>, chunk files will replace any existing file;
   ''' Otherwise, an exception will be thrown.
   ''' </param>
   ''' <exception cref="System.OverflowException">'ChunkSize' should be smaller than the Filesize.</exception>
   ''' <exception cref="System.IO.IOException"></exception>
   Public Sub SplitFile(ByVal InputFile As String,
                        ByVal ChunkSize As Long,
                        Optional ByVal ChunkName As String = Nothing,
                        Optional ByVal ChunkExt As String = Nothing,
                        Optional ByVal Overwrite As Boolean = False)

       ' FileInfo instance of the input file.
       Dim fInfo As New IO.FileInfo(InputFile)

       ' The buffer to read data and write the chunks.
       Dim Buffer As Byte() = New Byte() {}

       ' The buffer length.
       Dim BufferSize As Integer = 1048576 ' 1048576 = 1 mb | 33554432 = 32 mb | 67108864 = 64 mb

       ' Counts the length of the current chunk file.
       Dim BytesWritten As Long = 0L

       ' The total amount of chunks to create.
       Dim ChunkCount As Integer = CInt(Math.Floor(fInfo.Length / ChunkSize))

       ' Keeps track of the current chunk.
       Dim ChunkIndex As Integer = 0I

       ' A zero-filled string to enumerate the chunk files.
       Dim Zeros As String = String.Empty

       ' The given filename for each chunk.
       Dim ChunkFile As String = String.Empty

       ' The chunk file basename.
       ChunkName = If(String.IsNullOrEmpty(ChunkName),
                      IO.Path.Combine(fInfo.DirectoryName, IO.Path.GetFileNameWithoutExtension(fInfo.Name)),
                      IO.Path.Combine(fInfo.DirectoryName, ChunkName))

       ' The chunk file extension.
       ChunkExt = If(String.IsNullOrEmpty(ChunkExt),
                     fInfo.Extension.Substring(1I),
                     ChunkExt)

       ' If ChunkSize is bigger than filesize then...
       If ChunkSize >= fInfo.Length Then
           Throw New OverflowException("'ChunkSize' should be smaller than the Filesize.")
           Exit Sub

           ' For cases where a chunksize is smaller than the buffersize.
       ElseIf ChunkSize < BufferSize Then
           BufferSize = CInt(ChunkSize)

       End If ' ChunkSize <>...

       ' If not file-overwrite is allowed then...
       If Not Overwrite Then

           For Index As Integer = 0I To (ChunkCount)

               ' Set chunk filename.
               Zeros = New String("0", CStr(ChunkCount).Length - CStr(Index + 1I).Length)
               ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(Index + 1I), ChunkExt)

               ' If chunk file already exists then...
               If IO.File.Exists(ChunkFile) Then

                   Throw New IO.IOException(String.Format("File already exist: {0}", ChunkFile))
                   Exit Sub

               End If ' IO.File.Exists(ChunkFile)

           Next Index

           Zeros = String.Empty
           ChunkFile = String.Empty

       End If ' Overwrite

       ' Open the file to start reading bytes.
       Using InputStream As New IO.FileStream(fInfo.FullName, IO.FileMode.Open)

           Using BinaryReader As New IO.BinaryReader(InputStream)

               While (InputStream.Position < InputStream.Length)

                   ' Set chunk filename.
                   Zeros = New String("0", CStr(ChunkCount).Length - CStr(ChunkIndex + 1I).Length)
                   ChunkFile = String.Format("{0}.{1}.{2}", ChunkName, Zeros & CStr(ChunkIndex + 1I), ChunkExt)

                   ' Reset written byte-length counter.
                   BytesWritten = 0L

                   ' Create the chunk file to Write the bytes.
                   Using OutputStream As New IO.FileStream(ChunkFile, IO.FileMode.Create)

                       Using BinaryWriter As New IO.BinaryWriter(OutputStream)

                           ' Read until reached the end-bytes of the input file.
                           While (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)

                               ' Read bytes from the original file (BufferSize byte-length).
                               Buffer = BinaryReader.ReadBytes(BufferSize)

                               ' Write those bytes in the chunk file.
                               BinaryWriter.Write(Buffer)

                               ' Increment the size counter.
                               BytesWritten += Buffer.Count

                           End While ' (BytesWritten < ChunkSize) AndAlso (InputStream.Position < InputStream.Length)

                           OutputStream.Flush()

                       End Using ' BinaryWriter

                   End Using ' OutputStream

                   ChunkIndex += 1I 'Increment file counter

               End While ' InputStream.Position < InputStream.Length

           End Using ' BinaryReader

       End Using ' InputStream

   End Sub

Saludos.
#6740
Cita de: engel lex en 10 Agosto 2014, 10:18 AMcreo que va contra las reglas del foro entregar el código listo (no se si aplica a este sub foro, creo que no ya que Eleкtro creo que lo hace) pero tu sabes por todo el asunto que este es un lugar para aprender y eso...

Buenas

Me gustaría aclarar que NO está prohibido entregar códigos completos (trabajos echos, por así decirlo), cualquier tipo de ayuda es bienvenida ya sea un pequeño código o una aplicación entera con su código fuente, lo que está más o menos prohibido es pedir el trabajo echo (al pedir que los demás te hagan todo el trabajo se estará inflingiendo otro tipo de normas, por ende...).

Estás son dos normas muy importantes que deben tener en cuenta al formular preguntas:
Cita de: http://foro.elhacker.net/scripting/normas_del_tablon_leer_antes_de_postear-t201567.0.html• Buscar información en el buscador del foro y en los motores de búsqueda antes de formular una pregunta.
• Se pregunta por conceptos abstractos. Aquí no estamos para hacerle el trabajo a nadie

PD: Gracias por colaborar en el foro, pero proporcionar código no es motivo para sancionar a un usuario.

Saludos!