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

#6671
He escrito este ejemplo para mostrar como se puede compartir un espacio de memoria que puede ser leido por diferentes aplicaciones:



Esta sería la aplicación número 1, creen un nuevo proyecto, copien y compilen este Form:

Código (vbnet) [Seleccionar]
' Example of sharing memory across different running applications.
' By Elektro
'
' *************************
' This is the Application 1
' *************************

#Region " Imports "

Imports System.IO.MemoryMappedFiles

#End Region

#Region " Application 2 "

''' <summary>
''' Class MemoryMappedFile_Form1.
''' This should be the Class used to compile our first application.
''' </summary>
Public Class MemoryMappedFile_Form1

    ' The controls to create on execution-time.
    Dim WithEvents btMakeFile As New Button ' Writes the memory.
    Dim WithEvents btReadFile As New Button ' Reads the memory.
    Dim tbMessage As New TextBox ' Determines the string to map into memory.
    Dim tbReceptor As New TextBox ' Print the memory read's result.
    Dim lbInfoButtons As New Label ' Informs the user with a usage hint for the buttons.
    Dim lbInfotbMessage As New Label ' Informs the user with a usage hint for 'tbMessage'.

    ''' <summary>
    ''' Indicates the name of our memory-file.
    ''' </summary>
    Private ReadOnly MemoryName As String = "My Memory-File Name"

    ''' <summary>
    ''' Indicates the memory buffersize to store the <see cref="MemoryName"/>, in bytes.
    ''' </summary>
    Private ReadOnly MemoryBufferSize As Integer = 1024I

    ''' <summary>
    ''' Indicates the string to map in memory.
    ''' </summary>
    Private ReadOnly Property strMessage As String
        Get
            Return tbMessage.Text
        End Get
    End Property

    ''' <summary>
    ''' Initializes a new instance of the <see cref="MemoryMappedFile_Form1"/> class.
    ''' </summary>
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Set the properties of the controls.
        With lbInfotbMessage
            .Location = New Point(20, 10)
            .Text = "Type in this TextBox the message to write in memory:"
            .AutoSize = True
            ' .Size = tbReceptor.Size
        End With
        With tbMessage
            .Text = "Hello world from application one!"
            .Location = New Point(20, 30)
            .Size = New Size(310, Me.tbMessage.Height)
        End With
        With btMakeFile
            .Text = "Write Memory"
            .Size = New Size(130, 45)
            .Location = New Point(20, 50)
        End With
        With btReadFile
            .Text = "Read Memory"
            .Size = New Size(130, 45)
            .Location = New Point(200, 50)
        End With
        With tbReceptor
            .Location = New Point(20, 130)
            .Size = New Size(310, 100)
            .Multiline = True
        End With
        With lbInfoButtons
            .Location = New Point(tbReceptor.Location.X, tbReceptor.Location.Y - 30)
            .Text = "Press '" & btMakeFile.Text & "' button to create the memory file, that memory can be read from both applications."
            .AutoSize = False
            .Size = tbReceptor.Size
        End With

        ' Set the Form properties.
        With Me
            .Text = "Application 1"
            .Size = New Size(365, 300)
            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
            .MaximizeBox = False
            .StartPosition = FormStartPosition.CenterScreen
        End With

        ' Add the controls on the UI.
        Me.Controls.AddRange({lbInfotbMessage, tbMessage, btMakeFile, btReadFile, tbReceptor, lbInfoButtons})

    End Sub

    ''' <summary>
    ''' Writes a byte sequence into a <see cref="MemoryMappedFile"/>.
    ''' </summary>
    ''' <param name="Name">Indicates the name to assign the <see cref="MemoryMappedFile"/>.</param>
    ''' <param name="BufferLength">Indicates the <see cref="MemoryMappedFile"/> buffer-length to write in.</param>
    ''' <param name="Data">Indicates the byte-data to write inside the <see cref="MemoryMappedFile"/>.</param>
    Private Sub MakeMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer, ByVal Data As Byte())

        ' Create or open the memory-mapped file.
        Dim MessageFile As MemoryMappedFile =
            MemoryMappedFile.CreateOrOpen(Name, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)

        ' Write the byte-sequence into memory.
        Using Writer As MemoryMappedViewAccessor =
            MessageFile.CreateViewAccessor(0L, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)

            ' Firstly fill with null all the buffer.
            Writer.WriteArray(Of Byte)(0L, System.Text.Encoding.ASCII.GetBytes(New String(Nothing, Me.MemoryBufferSize)), 0I, Me.MemoryBufferSize)

            ' Secondly write the byte-data.
            Writer.WriteArray(Of Byte)(0L, Data, 0I, Data.Length)

        End Using ' Writer

    End Sub

    ''' <summary>
    ''' Reads a byte-sequence from a <see cref="MemoryMappedFile"/>.
    ''' </summary>
    ''' <param name="Name">Indicates an existing <see cref="MemoryMappedFile"/> assigned name.</param>
    ''' <param name="BufferLength">The buffer-length to read in.</param>
    ''' <returns>System.Byte().</returns>
    Private Function ReadMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer) As Byte()

        Try
            Using MemoryFile As MemoryMappedFile =
                MemoryMappedFile.OpenExisting(Name, MemoryMappedFileRights.Read)

                Using Reader As MemoryMappedViewAccessor =
                    MemoryFile.CreateViewAccessor(0L, BufferLength, MemoryMappedFileAccess.Read)

                    Dim ReadBytes As Byte() = New Byte(BufferLength - 1I) {}
                    Reader.ReadArray(Of Byte)(0L, ReadBytes, 0I, ReadBytes.Length)
                    Return ReadBytes

                End Using ' Reader

            End Using ' MemoryFile

        Catch ex As IO.FileNotFoundException
            Throw
            Return Nothing

        End Try

    End Function

    ''' <summary>
    ''' Handles the 'Click' event of the 'btMakeFile' control.
    ''' </summary>
    Private Sub btMakeFile_Click() Handles btMakeFile.Click

        ' Get the byte-data to create the memory-mapped file.
        Dim WriteData As Byte() = System.Text.Encoding.ASCII.GetBytes(Me.strMessage)

        ' Create the memory-mapped file.
        Me.MakeMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize, Data:=WriteData)

    End Sub

    ''' <summary>
    ''' Handles the 'Click' event of the 'btReadFile' control.
    ''' </summary>
    Private Sub btReadFile_Click() Handles btReadFile.Click


        Dim ReadBytes As Byte()

        Try ' Read the byte-sequence from memory.
            ReadBytes = ReadMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize)

        Catch ex As IO.FileNotFoundException
            Me.tbReceptor.Text = "Memory-mapped file does not exist."
            Exit Sub

        End Try

        ' Convert the bytes to String.
        Dim Message As String = System.Text.Encoding.ASCII.GetString(ReadBytes.ToArray)

        ' Remove null chars (leading zero-bytes)
        Message = Message.Trim({ControlChars.NullChar})

        ' Print the message.
        tbReceptor.Text = Message

    End Sub

End Class

#End Region


Esta sería la aplicación número 2, creen un nuevo proyecto, copien y compilen este Form:

Código (vbnet) [Seleccionar]
' Example of sharing memory across different running applications.
' By Elektro
'
' *************************
' This is the Application 2
' *************************

#Region " Imports "

Imports System.IO.MemoryMappedFiles

#End Region

#Region " Application 2 "

''' <summary>
''' Class MemoryMappedFile_Form2.
''' This should be the Class used to compile our first application.
''' </summary>
Public Class MemoryMappedFile_Form2

    ' The controls to create on execution-time.
    Dim WithEvents btMakeFile As New Button ' Writes the memory.
    Dim WithEvents btReadFile As New Button ' Reads the memory.
    Dim tbMessage As New TextBox ' Determines the string to map into memory.
    Dim tbReceptor As New TextBox ' Print the memory read's result.
    Dim lbInfoButtons As New Label ' Informs the user with a usage hint for the buttons.
    Dim lbInfotbMessage As New Label ' Informs the user with a usage hint for 'tbMessage'.

    ''' <summary>
    ''' Indicates the name of our memory-file.
    ''' </summary>
    Private ReadOnly MemoryName As String = "My Memory-File Name"

    ''' <summary>
    ''' Indicates the memory buffersize to store the <see cref="MemoryName"/>, in bytes.
    ''' </summary>
    Private ReadOnly MemoryBufferSize As Integer = 1024I

    ''' <summary>
    ''' Indicates the string to map in memory.
    ''' </summary>
    Private ReadOnly Property strMessage As String
        Get
            Return tbMessage.Text
        End Get
    End Property

    ''' <summary>
    ''' Initializes a new instance of the <see cref="MemoryMappedFile_Form2"/> class.
    ''' </summary>
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Set the properties of the controls.
        With lbInfotbMessage
            .Location = New Point(20, 10)
            .Text = "Type in this TextBox the message to write in memory:"
            .AutoSize = True
            ' .Size = tbReceptor.Size
        End With
        With tbMessage
            .Text = "Hello world from application two!"
            .Location = New Point(20, 30)
            .Size = New Size(310, Me.tbMessage.Height)
        End With
        With btMakeFile
            .Text = "Write Memory"
            .Size = New Size(130, 45)
            .Location = New Point(20, 50)
        End With
        With btReadFile
            .Text = "Read Memory"
            .Size = New Size(130, 45)
            .Location = New Point(200, 50)
        End With
        With tbReceptor
            .Location = New Point(20, 130)
            .Size = New Size(310, 100)
            .Multiline = True
        End With
        With lbInfoButtons
            .Location = New Point(tbReceptor.Location.X, tbReceptor.Location.Y - 30)
            .Text = "Press '" & btMakeFile.Text & "' button to create the memory file, that memory can be read from both applications."
            .AutoSize = False
            .Size = tbReceptor.Size
        End With

        ' Set the Form properties.
        With Me
            .Text = "Application 2"
            .Size = New Size(365, 300)
            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
            .MaximizeBox = False
            .StartPosition = FormStartPosition.CenterScreen
        End With

        ' Add the controls on the UI.
        Me.Controls.AddRange({lbInfotbMessage, tbMessage, btMakeFile, btReadFile, tbReceptor, lbInfoButtons})

    End Sub

    ''' <summary>
    ''' Writes a byte sequence into a <see cref="MemoryMappedFile"/>.
    ''' </summary>
    ''' <param name="Name">Indicates the name to assign the <see cref="MemoryMappedFile"/>.</param>
    ''' <param name="BufferLength">Indicates the <see cref="MemoryMappedFile"/> buffer-length to write in.</param>
    ''' <param name="Data">Indicates the byte-data to write inside the <see cref="MemoryMappedFile"/>.</param>
    Private Sub MakeMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer, ByVal Data As Byte())

        ' Create or open the memory-mapped file.
        Dim MessageFile As MemoryMappedFile =
            MemoryMappedFile.CreateOrOpen(Name, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)

        ' Write the byte-sequence into memory.
        Using Writer As MemoryMappedViewAccessor =
            MessageFile.CreateViewAccessor(0L, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)

            ' Firstly fill with null all the buffer.
            Writer.WriteArray(Of Byte)(0L, System.Text.Encoding.ASCII.GetBytes(New String(Nothing, Me.MemoryBufferSize)), 0I, Me.MemoryBufferSize)

            ' Secondly write the byte-data.
            Writer.WriteArray(Of Byte)(0L, Data, 0I, Data.Length)

        End Using ' Writer

    End Sub

    ''' <summary>
    ''' Reads a byte-sequence from a <see cref="MemoryMappedFile"/>.
    ''' </summary>
    ''' <param name="Name">Indicates an existing <see cref="MemoryMappedFile"/> assigned name.</param>
    ''' <param name="BufferLength">The buffer-length to read in.</param>
    ''' <returns>System.Byte().</returns>
    Private Function ReadMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer) As Byte()

        Try
            Using MemoryFile As MemoryMappedFile =
                MemoryMappedFile.OpenExisting(Name, MemoryMappedFileRights.Read)

                Using Reader As MemoryMappedViewAccessor =
                    MemoryFile.CreateViewAccessor(0L, BufferLength, MemoryMappedFileAccess.Read)

                    Dim ReadBytes As Byte() = New Byte(BufferLength - 1I) {}
                    Reader.ReadArray(Of Byte)(0L, ReadBytes, 0I, ReadBytes.Length)
                    Return ReadBytes

                End Using ' Reader

            End Using ' MemoryFile

        Catch ex As IO.FileNotFoundException
            Throw
            Return Nothing

        End Try

    End Function

    ''' <summary>
    ''' Handles the 'Click' event of the 'btMakeFile' control.
    ''' </summary>
    Private Sub btMakeFile_Click() Handles btMakeFile.Click

        ' Get the byte-data to create the memory-mapped file.
        Dim WriteData As Byte() = System.Text.Encoding.ASCII.GetBytes(Me.strMessage)

        ' Create the memory-mapped file.
        Me.MakeMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize, Data:=WriteData)

    End Sub

    ''' <summary>
    ''' Handles the 'Click' event of the 'btReadFile' control.
    ''' </summary>
    Private Sub btReadFile_Click() Handles btReadFile.Click


        Dim ReadBytes As Byte()

        Try ' Read the byte-sequence from memory.
            ReadBytes = ReadMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize)

        Catch ex As IO.FileNotFoundException
            Me.tbReceptor.Text = "Memory-mapped file does not exist."
            Exit Sub

        End Try

        ' Convert the bytes to String.
        Dim Message As String = System.Text.Encoding.ASCII.GetString(ReadBytes.ToArray)

        ' Remove null chars (leading zero-bytes)
        Message = Message.Trim({ControlChars.NullChar})

        ' Print the message.
        tbReceptor.Text = Message

    End Sub

End Class

#End Region


Ahora ya solo tienen que ejecutar ambas aplicaciones para testear.

Saludos!
#6672
Un ejemplo de uso de la librería MagicGraphics: http://www.codeproject.com/Articles/19188/Magic-Graphics








Escribí este Form para jugar un poco con la funcionalidad de esta librería, la verdad es que es muy sencillo.



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

    Private WithEvents RotationTimer As New Timer With {.Enabled = True, .Interval = 25}

    Dim SC As MagicGraphics.ShapeContainer

    Private Sub Tst_Shown() Handles MyBase.Shown

        SC = New MagicGraphics.ShapeContainer(PictureBox1.CreateGraphics, PictureBox1.Width, PictureBox1.Height, Color.Black, PictureBox1.Image)
        PictureBox1.Image = SC.BMP
        SC.AutoFlush = False

        Dim Sq As New MagicGraphics.Rectangle(New Pen(Color.Black, 3), Brushes.Aqua, 60, 20, 50, 50)
        Sq.FillingBrush = New Drawing2D.LinearGradientBrush(New Point(0, 0), New Point(60, 0), Color.Yellow, Color.Red)
        SC.AddShape(Sq)
        Dim El As New MagicGraphics.Ellipse(New Pen(Color.Black, 3), Brushes.Olive, 60, 88, 50, 71)
        El.FillingBrush = New Drawing2D.LinearGradientBrush(New Point(0, 0), New Point(30, 0), Color.Red, Color.SteelBlue)
        SC.AddShape(El)

        RotationTimer.Start()

    End Sub


    Private Sub RotationTimer_Tick() Handles RotationTimer.Tick

        Static Direction As Integer = 1I ' 0 = Left, 1 = Right

        For X As Integer = 0I To (SC.ShapesL.Count - 1)

            Dim shp As MagicGraphics.Shape = SC.ShapesL(X)

            shp.Rotate(-8)

            If shp.Location.X > (PictureBox1.Width - shp.Width) Then
                Direction = 1I ' Right

            ElseIf shp.Location.X < PictureBox1.Location.X Then
                Direction = 0I ' Left

            End If

            If Direction = 0 Then
                shp.Move(shp.Location.X + 2, shp.Location.Y)

            Else
                shp.Move(shp.Location.X - 2, shp.Location.Y)

            End If

            ' Debug.WriteLine(String.Format("Shape {0} Rotation: {1}", CStr(X), shp.Rotation))

        Next X

        SC.Flush()

    End Sub

End Class
#6673
Cita de: luis456 en 19 Agosto 2014, 13:31 PM
Mil gracias de nuevo ahora si pude hacerlo funcionar :)

Bien aca donde me pones esto , es lo debería de cambiar por mi variable " result " que es la que tiene los números después de efectuada la operación que hago en mi programa ?

Código (vbnet) [Seleccionar]
ReadOnly FixedValues As Integer() = {1, 5, 19, 22, 34, 55, 66, 88, 99, etc...}

¿A cual de las miles de variables que bautizaste con el nombre de "Result" te refieres? :P

Supongo que si, en la variable FixedValues debes especificarle los numeros que se tomarán para hacer las combinaciones, en tu ejemplo pusiste del 1 al 30, no se si harás eso con la variable "result" que mencionas, pero creo que ya te hiciste una idea de lo que debe ir en esa variable FixedValues (valores fijos).

Cita de: luis456 en 19 Agosto 2014, 13:31 PMpor lo demas funciona como queria

Me alegro de oir eso

PD: Por si acaso te recuerdo que para ordenar de mayor a menor lo tienes facil usando una LINQ-query:
Código (vbnet) [Seleccionar]
dim values as integer() = (from n as integer in TUSNUMEROS order by n ascending).toarray

o el método Sort, en una lista.

Saludos!
#6674
Windows / Re: Renombrar ficheros
19 Agosto 2014, 13:35 PM
Si tienes una colección de cientos o miles de canciones entonces hay bastantes probabilidades de que el campo "ARTISTA" contenga guiones (ej: "Pepito De-Maria - Canción del verano"), y eso imposibilitaría un renombrado correcto porque es imposible saber cuantos guiones existen antes del quión que realmente separa el título del artista, así que prefiero evitar darte una solución sencilla (un script) y sugerirte que utilices la aplicación Renamer Pro: http://www.den4b.com/?x=products&product=renamer (el cual es muy sencillo de usar)

Junto a este preset que acabo de hacer para la ocasión:

ARTIST - Title Words.rnp
[Rule0]
ID=Case
Config=WHAT:3;SKIPEXTENSION:0;EXTENSIONALWAYSLOWERCASE:1;EXTENSIONALWAYSUPPERCASE:0;FORCECASE:0;FRAGMENTSTEXT:
Marked=1

[Rule1]
ID=RegEx
Config=expression:%28%2E%2B%29%5C%2D;REPLACE:%5CU%241%2D;CASESENSITIVE:0;SKIPEXTENSION:1
Marked=1


Primero capitalizo cada palabra del string, y luego utilizo la siguiente expresión regular para poner el campo "artista" en UPPERCASE:

Patrón de búsqueda: (.+)-
Reemplazamiento...: \U$1-


Todo esto lo puedes hacer en cualquier lenguaje de programación, pero te sugiero utilizar este programa para tener mayor control de las reglas de renombrado y sobretodo para poder visualizar una Preview del resultado antes de renombrar.



Saludos!
#6675
Me encontré por ahí un ErrorProvider extendido, ya no recuerdo donde lo encontré, y la documentación es... bueno, muy pobre, pero es facil de usar y sencillo de entender a pesar de ello:

'Following class is inherited from basic ErrorProvider class
#Region "Error Provider Extended"
Public Class ErrorProviderExtended
   Inherits System.Windows.Forms.ErrorProvider
   Private _validationcontrols As New ValidationControlCollection
   Private _summarymessage As String = "Please enter following mandatory fields,"

   'This property will be used for displaying a summary message about all empty fields
   'Default value is "Please enter following mandatory fields,". You can set any other
   'message using this property.
   Public Property SummaryMessage() As String
       Get
           Return _summarymessage
       End Get
       Set(ByVal Value As String)
           _summarymessage = Value
       End Set
   End Property

   'Controls property is of type ValidationControlCollection which is inherited from CollectionBase
   'Controls holds all those objects which should be validated.
   Public Property Controls() As ValidationControlCollection
       Get
           Return _validationcontrols
       End Get
       Set(ByVal Value As ValidationControlCollection)
           _validationcontrols = Value
       End Set
   End Property

   'Following function returns true if all fields on form are entered.
   'If not all fields are entered, this function displays a message box which contains all those field names
   'which are empty and returns FALSE.
   Public Function CheckAndShowSummaryErrorMessage() As Boolean
       If Controls.Count <= 0 Then
           Return True
       End If
       Dim i As Integer
       Dim msg As String = SummaryMessage + vbNewLine + vbNewLine
       Dim berrors As Boolean = False
       For i = 0 To Controls.Count - 1
           If Controls(i).Validate Then
               If Trim(Controls(i).ControlObj.text) = "" Then
                   msg &= "> " & Controls(i).DisplayName & vbNewLine
                   SetError(Controls(i).ControlObj, Controls(i).ErrorMessage)
                   berrors = True
               Else
                   SetError(Controls(i).ControlObj, "")
               End If
           Else
               SetError(Controls(i).ControlObj, "")
           End If
       Next
       If berrors Then
           System.Windows.Forms.MessageBox.Show(msg, "Missing Information", Windows.Forms.MessageBoxButtons.OK, Windows.Forms.MessageBoxIcon.Stop)
           Return False
       Else
           Return True
       End If
   End Function

   'Following function clears error messages from all controls.
   Public Sub ClearAllErrorMessages()
       Dim i As Integer
       For i = 0 To Controls.Count - 1
           SetError(Controls(i).ControlObj, "")
       Next
   End Sub

   'This function hooks validation event with all controls.
   Public Sub SetErrorEvents()
       Dim i As Integer
       For i = 0 To Controls.Count - 1
           AddHandler CType(Controls(i).ControlObj, System.Windows.Forms.Control).Validating, AddressOf Validation_Event
       Next
   End Sub

   'Following event is hooked for all controls, it sets an error message with the use of ErrorProvider.
   Private Sub Validation_Event(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) 'Handles txtCompanyName.Validating
       If Controls(sender).Validate Then
           If Trim(sender.Text) = "" Then
               MyBase.SetError(sender, Controls(sender).ErrorMessage)
           Else
               MyBase.SetError(sender, "")
           End If
       End If
   End Sub
End Class
#End Region

'Following class is inherited from CollectionBase class. It is used for holding all Validation Controls.
'This class is collection of ValidationControl class objects.
'This class is used by ErrorProviderExtended class.
#Region "ValidationControlCollection"
Public Class ValidationControlCollection
   Inherits CollectionBase
   Default Public Property Item(ByVal ListIndex As Integer) As ValidationControl
       Get
           Return Me.List(ListIndex)
       End Get
       Set(ByVal Value As ValidationControl)
           Me.List(ListIndex) = Value
       End Set
   End Property


   Default Public Property Item(ByVal pControl As Object) As ValidationControl
       Get
           If IsNothing(pControl) Then
               Return Nothing
           End If

           If GetIndex(pControl.Name) < 0 Then
               Return New ValidationControl
           End If
           Return Me.List(GetIndex(pControl.Name))
       End Get
       Set(ByVal Value As ValidationControl)
           If IsNothing(pControl) Then Exit Property
           If GetIndex(pControl.Name) < 0 Then
               Exit Property
           End If
           Me.List(GetIndex(pControl.Name)) = Value
       End Set
   End Property
   Function GetIndex(ByVal ControlName As String) As Integer
       Dim i As Integer
       For i = 0 To Count - 1
           If Item(i).ControlObj.name.toupper = ControlName.ToUpper Then
               Return i
           End If
       Next
       Return -1
   End Function
   Public Sub Add(ByRef pControl As Object, ByVal pDisplayName As String)
       If IsNothing(pControl) Then Exit Sub
       Dim obj As New ValidationControl
       obj.ControlObj = pControl
       obj.DisplayName = pDisplayName
       obj.ErrorMessage = "Please enter " + pDisplayName
       Me.List.Add(obj)
   End Sub

   Public Sub Add(ByRef pControl As Object, ByVal pDisplayName As String, ByVal pErrorMessage As String)
       If IsNothing(pControl) Then Exit Sub
       Dim obj As New ValidationControl
       obj.ControlObj = pControl
       obj.DisplayName = pDisplayName
       obj.ErrorMessage = pErrorMessage
       Me.List.Add(obj)
   End Sub
   Public Sub Add(ByRef pControl As Object)
       If IsNothing(pControl) Then Exit Sub
       Dim obj As New ValidationControl
       obj.ControlObj = pControl
       obj.DisplayName = pControl.Name
       obj.ErrorMessage = "Please enter " + pControl.Name
       Me.List.Add(obj)
   End Sub
   Public Sub Add(ByVal pControl As ValidationControl)
       If IsNothing(pControl) Then Exit Sub
       Me.List.Add(pControl)
   End Sub
   Public Sub Remove(ByVal pControl As Object)
       If IsNothing(pControl) Then Exit Sub
       Dim i As Integer = Me.GetIndex(pControl.Name)
       If i >= 0 Then
           Me.List.RemoveAt(i)
       End If
   End Sub
End Class
#End Region

'ValidationControl class is used to hold any control from windows form.
'It holds any control in ControlObj property.
#Region "ValidationControl"
Public Class ValidationControl
   Private _control As Object
   Private _displayname As String
   Private _errormessage As String
   Private _validate As Boolean = True

   'Validate property decides weather control is to be validated. Default value is TRUE.
   Public Property Validate() As Boolean
       Get
           Return _validate
       End Get
       Set(ByVal Value As Boolean)
           _validate = Value
       End Set
   End Property

   'ControlObj is a control from windows form which is to be validated.
   'For example txtStudentName
   Public Property ControlObj() As Object
       Get
           Return _control
       End Get
       Set(ByVal Value As Object)
           _control = Value
       End Set
   End Property

   'DisplayName property is used for displaying summary message to user.
   'For example, for txtStudentName you can set 'Student Full Name' as field name.
   'This field name will be displayed in summary message.
   Public Property DisplayName() As String
       Get
           Return _displayname
       End Get
       Set(ByVal Value As String)
           _displayname = Value
       End Set
   End Property

   'ErrorMessage is also used for displaying summary message.
   'For example, you can enter 'Student Name is mandatory' as an error message.
   Public Property ErrorMessage() As String
       Get
           Return _errormessage
       End Get
       Set(ByVal Value As String)
           _errormessage = Value
       End Set
   End Property
End Class
#End Region



EDITO: Ya lo he documentado yo así rapidamente:

Código (vbnet) [Seleccionar]
#Region "Error Provider Extended"

''' <summary>
''' Provides a user interface for indicating that a control on a form has an error associated with it.
''' </summary>
Public Class ErrorProviderExtended

   Inherits System.Windows.Forms.ErrorProvider
   Private _validationcontrols As New ValidationControlCollection
   Private _summarymessage As String = "Please enter following mandatory fields,"

   ''' <summary>
   ''' Gets or sets the summary message.
   ''' This property will be used for displaying a summary message about all empty fields.
   ''' Default value is "Please enter following mandatory fields,".
   ''' You can set any other message using this property.
   ''' </summary>
   ''' <value>The summary message.</value>
   Public Property SummaryMessage() As String
       Get
           Return _summarymessage
       End Get
       Set(ByVal Value As String)
           _summarymessage = Value
       End Set
   End Property

   ''' <summary>
   ''' Gets or sets the controls which should be validated.
   ''' </summary>
   ''' <value>The controls.</value>
   Public Property Controls() As ValidationControlCollection
       Get
           Return _validationcontrols
       End Get
       Set(ByVal Value As ValidationControlCollection)
           _validationcontrols = Value
       End Set
   End Property

   ''' <summary>
   ''' Checks the and show summary error message.
   ''' </summary>
   ''' <param name="ShowMessage">
   ''' If set to <c>true</c>, This function displays a message box which contains all the field names which are empty.
   ''' </param>
   ''' <returns><c>true</c> if all fields on form are entered, <c>false</c> otherwise.</returns>
   Public Function CheckAndShowSummaryErrorMessage(Optional ByVal ShowMessage As Boolean = False) As Boolean

       If Controls.Count <= 0 Then
           Return True
       End If

       Dim i As Integer
       Dim msg As String = SummaryMessage + vbNewLine + vbNewLine
       Dim berrors As Boolean = False

       For i = 0 To Controls.Count - 1

           If Controls(i).Validate Then
               If Trim(Controls(i).ControlObj.text) = "" Then
                   If ShowMessage Then
                       msg &= "> " & Controls(i).DisplayName & vbNewLine
                   End If
                   SetError(Controls(i).ControlObj, Controls(i).ErrorMessage)
                   berrors = True
               Else
                   SetError(Controls(i).ControlObj, "")
               End If
           Else
               SetError(Controls(i).ControlObj, "")
           End If

       Next i

       If berrors Then
           If ShowMessage Then
               MessageBox.Show(msg, "Missing Information", MessageBoxButtons.OK, MessageBoxIcon.Stop)
           End If
           Return False
       Else
           Return True
       End If

   End Function

   ''' <summary>
   ''' Clears error messages from all controls.
   ''' </summary>
   Public Sub ClearAllErrorMessages()

       Dim i As Integer
       For i = 0 To Controls.Count - 1
           SetError(Controls(i).ControlObj, "")
       Next

   End Sub

   ''' <summary>
   ''' Hooks validation event with all controls.
   ''' </summary>
   Public Sub SetErrorEvents()

       Dim i As Integer
       For i = 0 To Controls.Count - 1
           AddHandler CType(Controls(i).ControlObj, System.Windows.Forms.Control).Validating, AddressOf Validation_Event
       Next

   End Sub

   ''' <summary>
   ''' Handles the Event event of the Validation control.
   ''' This event is hooked for all controls,
   ''' it sets an error message with the use of ErrorProvider
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
   Private Sub Validation_Event(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)

       If Controls(sender).Validate Then
           If Trim(sender.Text) = "" Then
               MyBase.SetError(sender, Controls(sender).ErrorMessage)
           Else
               MyBase.SetError(sender, "")
           End If
       End If

   End Sub

End Class

#End Region

#Region "ValidationControlCollection"

''' <summary>
''' This class is used for holding all Validation Controls.
''' This class is collection of 'ValidationControl' class objects.
''' This class is used by 'ErrorProviderExtended' class.
''' </summary>
Public Class ValidationControlCollection : Inherits CollectionBase

   Default Public Property Item(ByVal ListIndex As Integer) As ValidationControl
       Get
           Return Me.List(ListIndex)
       End Get
       Set(ByVal Value As ValidationControl)
           Me.List(ListIndex) = Value
       End Set
   End Property

   Default Public Property Item(ByVal pControl As Object) As ValidationControl
       Get
           If IsNothing(pControl) Then
               Return Nothing
           End If

           If GetIndex(pControl.Name) < 0 Then
               Return New ValidationControl
           End If
           Return Me.List(GetIndex(pControl.Name))
       End Get
       Set(ByVal Value As ValidationControl)
           If IsNothing(pControl) Then Exit Property
           If GetIndex(pControl.Name) < 0 Then
               Exit Property
           End If
           Me.List(GetIndex(pControl.Name)) = Value
       End Set
   End Property

   Function GetIndex(ByVal ControlName As String) As Integer
       Dim i As Integer
       For i = 0 To Count - 1
           If Item(i).ControlObj.name.toupper = ControlName.ToUpper Then
               Return i
           End If
       Next
       Return -1
   End Function

   Public Sub Add(ByRef pControl As Object, ByVal pDisplayName As String)
       If IsNothing(pControl) Then Exit Sub
       Dim obj As New ValidationControl
       obj.ControlObj = pControl
       obj.DisplayName = pDisplayName
       obj.ErrorMessage = "Please enter " + pDisplayName
       Me.List.Add(obj)
   End Sub

   Public Sub Add(ByRef pControl As Object, ByVal pDisplayName As String, ByVal pErrorMessage As String)
       If IsNothing(pControl) Then Exit Sub
       Dim obj As New ValidationControl
       obj.ControlObj = pControl
       obj.DisplayName = pDisplayName
       obj.ErrorMessage = pErrorMessage
       Me.List.Add(obj)
   End Sub

   Public Sub Add(ByRef pControl As Object)
       If IsNothing(pControl) Then Exit Sub
       Dim obj As New ValidationControl
       obj.ControlObj = pControl
       obj.DisplayName = pControl.Name
       obj.ErrorMessage = "Please enter " + pControl.Name
       Me.List.Add(obj)
   End Sub

   Public Sub Add(ByVal pControl As ValidationControl)
       If IsNothing(pControl) Then Exit Sub
       Me.List.Add(pControl)
   End Sub

   Public Sub Remove(ByVal pControl As Object)
       If IsNothing(pControl) Then Exit Sub
       Dim i As Integer = Me.GetIndex(pControl.Name)
       If i >= 0 Then
           Me.List.RemoveAt(i)
       End If
   End Sub
End Class

#End Region

#Region "ValidationControl"

''' <summary>
''' ValidationControl class is used to hold any control from windows form.
''' 'It holds any control in 'ControlObj' property.
''' </summary>
Public Class ValidationControl

   Private _control As Object
   Private _displayname As String
   Private _errormessage As String
   Private _validate As Boolean = True

   ''' <summary>
   ''' Decides weather control is to be validated. Default value is TRUE.
   ''' </summary>
   ''' <value><c>true</c> if validate; otherwise, <c>false</c>.</value>
   Public Property Validate() As Boolean
       Get
           Return _validate
       End Get
       Set(ByVal Value As Boolean)
           _validate = Value
       End Set
   End Property

   ''' <summary>
   ''' ControlObj is a Control from windows form which is to be validated.
   ''' </summary>
   ''' <value>The control object.</value>
   Public Property ControlObj() As Object
       Get
           Return _control
       End Get
       Set(ByVal Value As Object)
           _control = Value
       End Set
   End Property

   ''' <summary>
   ''' DisplayName property is used for displaying summary message to user.
   ''' This field name will be displayed in summary message.
   ''' </summary>
   ''' <value>The display name.</value>
   Public Property DisplayName() As String
       Get
           Return _displayname
       End Get
       Set(ByVal Value As String)
           _displayname = Value
       End Set
   End Property

   ''' <summary>
   ''' ErrorMessage is also used for displaying summary message.
   ''' </summary>
   ''' <value>The error message.</value>
   Public Property ErrorMessage() As String
       Get
           Return _errormessage
       End Get
       Set(ByVal Value As String)
           _errormessage = Value
       End Set
   End Property

End Class

#End Region


Escribí este Form para probar su utilidad:



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

    ''' <summary>
    ''' The ErrorProviderExtended instance.
    ''' </summary>
    Private WithEvents MyErrorProvider As New ErrorProviderExtended

    ''' <summary>
    ''' Control to validate its content.
    ''' </summary>
    Private WithEvents tbValue As New TextBox

    ''' <summary>
    ''' Control that validates general errors.
    ''' </summary>
    Private WithEvents btValidator As New Button

    ''' <summary>
    ''' Control that reports the current error message.
    ''' </summary>
    Private lblError As New Label

    ''' <summary>
    ''' Control used to indicate a textbox hint.
    ''' </summary>
    Private lblHint As New Label

    ''' <summary>
    ''' This value determines whether exists errors that need to be fixed.
    ''' </summary>
    Dim ErrorExists As Boolean = False

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        With Me.lblHint
            .Location = New Point(10, 10)
            .Text = "Type an 'Int32' value:"
            .ForeColor = Color.WhiteSmoke
            .AutoSize = True
        End With

        With Me.tbValue
            .Location = New Point(15, 25)
            .Size = New Size(100, Me.tbValue.Height)
        End With

        With Me.lblError
            .Location = New Point(10, 50)
            .Text = ""
            .ForeColor = Color.WhiteSmoke
            .AutoSize = True
        End With

        With Me.btValidator
            .Location = New Point(Me.lblError.Location.X, Me.lblError.Location.Y + 20)
            .Text = "Validate"
            .FlatStyle = FlatStyle.System
        End With

        With Me
            .MaximizeBox = False
            .StartPosition = FormStartPosition.CenterScreen
            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
            .Size = New Point(220, 150)
            .BackColor = Color.FromArgb(34, 34, 36)
            .Controls.AddRange({Me.lblHint, Me.lblError, Me.tbValue, Me.btValidator})
        End With

    End Sub

    Private Sub Test_Load() Handles Me.Load

        With MyErrorProvider
            .Controls.Add(Me.tbValue, "Int32")
            .Controls(Me.tbValue).Validate = True
            .SummaryMessage = "Following fields are mandatory."
        End With

        ' Change the textbox text to produce an intentional error.
        tbValue.AppendText(" ")
        tbValue.Clear()

    End Sub

    Private Sub Button1_Click() _
    Handles btValidator.Click

        ' The following function checks all empty fields and returns TRUE if all fields are entered.
        ' If any mandotary field is empty this function displays a message and returns FALSE.
        If MyErrorProvider.CheckAndShowSummaryErrorMessage(ShowMessage:=True) Then

            If Not Me.ErrorExists Then
                MessageBox.Show("Data submited successfully.", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("Data cannot be submited, fix the error(s).", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

    ''' <summary>
    ''' Handles the TextChanged event of the tbValue control.
    ''' </summary>
    Private Sub tbValue_TextChanged(sender As Object, e As EventArgs) _
    Handles tbValue.TextChanged

        Dim Value As String = sender.text

        If String.IsNullOrEmpty(Value) Then
            MyErrorProvider.SetError(sender, "TextBox is empty.")

        ElseIf Not Single.TryParse(Value, New Single) Then
            MyErrorProvider.SetError(sender, "The value cannot contain letters.")

        ElseIf Single.TryParse(Value, New Single) Then

            If Value > Integer.MaxValue Then
                MyErrorProvider.SetError(sender, "Value is greater than " & CStr(Integer.MaxValue))
            Else ' Remove the error.
                MyErrorProvider.SetError(sender, String.Empty)
            End If

        Else ' Remove the error.
            MyErrorProvider.SetError(sender, String.Empty)

        End If

        Me.lblError.Text = MyErrorProvider.GetError(sender)

        If String.IsNullOrEmpty(Me.lblError.Text) Then
            Me.lblError.Text = "No errors :)"
            Me.ErrorExists = False
        Else
            Me.ErrorExists = True
        End If

    End Sub

End Class


#6676
Obtiene las expresiones XPath de un documento Html, usando la librería HtmlAgilityPack.

PD: Si encuentran algún fallo porfavor reportármelo, no conozco mucho el tema de los XPath.



Código (vbnet) [Seleccionar]
   ' Get Html XPaths
   ' By Elektro
   '
   ' Example Usage:
   '
   ' Dim Document As New HtmlAgilityPack.HtmlDocument
   ' Document.LoadHtml(IO.File.ReadAllText("C:\File.html"))
   ' Dim XpathList As List(Of String) = GetHtmlXPaths(Document)
   ' ListBox1.Items.AddRange((From XPath As String In XpathList Select XPath).ToArray)

   ''' <summary>
   ''' Gets all the XPath expressions of an <see cref="HtmlAgilityPack.HtmlDocument"/> document.
   ''' </summary>
   ''' <param name="Document">Indicates the <see cref="HtmlAgilityPack.HtmlDocument"/> document.</param>
   ''' <returns>List(Of System.String).</returns>
   Public Function GetHtmlXPaths(ByVal Document As HtmlAgilityPack.HtmlDocument) As List(Of String)

       Dim XPathList As New List(Of String)
       Dim XPath As String = String.Empty

       For Each Child As HtmlAgilityPack.HtmlNode In Document.DocumentNode.ChildNodes

           If Child.NodeType = HtmlAgilityPack.HtmlNodeType.Element Then
               GetHtmlXPaths(Child, XPathList, XPath)
           End If

       Next Child

       Return XPathList

   End Function

   ''' <summary>
   ''' Gets all the XPath expressions of an <see cref="HtmlAgilityPack.HtmlNode"/>.
   ''' </summary>
   ''' <param name="Node">Indicates the <see cref="HtmlAgilityPack.HtmlNode"/>.</param>
   ''' <param name="XPathList">Indicates a ByReffered XPath list as a <see cref="List(Of String)"/>.</param>
   ''' <param name="XPath">Indicates the current XPath.</param>
   Private Sub GetHtmlXPaths(ByVal Node As HtmlAgilityPack.HtmlNode,
                             ByRef XPathList As List(Of String),
                             Optional ByVal XPath As String = Nothing)

       XPath &= Node.XPath.Substring(Node.XPath.LastIndexOf("/"c))

       Const ClassNameFilter As String = "[@class='{0}']"
       Dim ClassName As String = Node.GetAttributeValue("class", String.Empty)

       If Not String.IsNullOrEmpty(ClassName) Then
           XPath &= String.Format(ClassNameFilter, ClassName)
       End If

       If Not XPathList.Contains(XPath) Then
           XPathList.Add(XPath)
       End If

       For Each Child As HtmlAgilityPack.HtmlNode In Node.ChildNodes

           If Child.NodeType = HtmlAgilityPack.HtmlNodeType.Element Then
               GetHtmlXPaths(Child, XPathList, XPath)
           End If

       Next Child

   End Sub
#6677
Convierte un String a HTMLDocument

Código (vbnet) [Seleccionar]
   ' String To HtmlDocument
   ' By Elektro
   '
   ' Example Usage:
   ' Dim Document As HtmlDocument = StringToHtmlDocument(IO.File.ReadAllText("C:\File.html", Text.Encoding.Default))
   '
   ''' <summary>
   ''' Converts a <see cref="String"/> to an <see cref="HTMLDocument"/>.
   ''' </summary>
   ''' <param name="str">Indicates the string.</param>
   ''' <returns>The <see cref="HTMLDocument"/> object.</returns>
   Public Function StringToHtmlDocument(ByVal str As String) As HtmlDocument

       Using wb As New WebBrowser

           wb.ScriptErrorsSuppressed = True
           wb.DocumentText = ""
           wb.Document.OpenNew(replaceInHistory:=True)
           wb.Document.Write(str)
           Return wb.Document

       End Using

   End Function





Obtiene los XPaths de un XMLDocument:



Código (vbnet) [Seleccionar]
   ' Get XPaths
   ' By Elektro
   '
   ' Example Usage:
   '
   ' Dim xDoc As New Xml.XmlDocument
   ' xDoc.Load("C:\File.xml")
   ' Dim XPathList As List(Of String) = GetXPaths(xDoc)
   ' ListBox1.Items.AddRange((From XPath As String In XPathList Select XPath).ToArray)

   ''' <summary>
   ''' Gets all the XPath expressions of an XML Document.
   ''' </summary>
   ''' <param name="Document">Indicates the XML document.</param>
   ''' <returns>List(Of System.String).</returns>
   Public Function GetXPaths(ByVal Document As Xml.XmlDocument) As List(Of String)

       Dim XPathList As New List(Of String)

       Dim XPath As String = String.Empty

       For Each Child As Xml.XmlNode In Document.ChildNodes

           If Child.NodeType = Xml.XmlNodeType.Element Then
               GetXPaths(Child, XPathList, XPath)
           End If

       Next ' child

       Return XPathList

   End Function

   ''' <summary>
   ''' Gets all the XPath expressions of an XML Node.
   ''' </summary>
   ''' <param name="Node">Indicates the XML node.</param>
   ''' <param name="XPathList">Indicates a ByReffered XPath list as a <see cref="List(Of String)"/>.</param>
   ''' <param name="XPath">Indicates the current XPath.</param>
   Private Sub GetXPaths(ByVal Node As Xml.XmlNode,
                         ByRef XPathList As List(Of String),
                         Optional ByVal XPath As String = Nothing)

       XPath &= "/" & Node.Name

       If Not XPathList.Contains(XPath) Then
           XPathList.Add(XPath)
       End If

       For Each Child As Xml.XmlNode In Node.ChildNodes

           If Child.NodeType = Xml.XmlNodeType.Element Then
               GetXPaths(Child, XPathList, XPath)
           End If

       Next ' child

   End Sub
#6678
Citarasumo que el programa lee que son números desde el 01 al 30 correlativamente ?

Tu input, del 1 al 30:
Cita de: luis456 en 15 Agosto 2014, 21:16 PMinput
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

Mi input, del 1 al 30:
Citar
Código (vbnet) [Seleccionar]
Enumerable.Range(1I, 30I).ToArray ' 1 to 30

Recuerda que el código que te he ofrecido solo es un algoritmo que mimica los pasos que has explicado en tu ejemplo, es decir: 30 combinaciones del 1 al 30, dando saltos de 3 posiciones, los combos de 10 numeros de longitud cada combo, y con numeros aleatorios dentro de un rango específico en los espacios libres a rellenar.




Citarno es la idea
¿Que te impide modificar manualmente el array?:

Código (vbnet) [Seleccionar]
ReadOnly FixedValues As Integer() = {1, 5, 19, 22, 34, 55, 66, 88, 99, etc...}

El código actuará (o debería actuar) de la misma manera.




Citardonde muestro los resultados  estoy poniendo esto pero solo me sale  " colección "

Es que le estás intentando pasar una colección que tiene más colecciones dentro, es decir, una Lista de Listas (List(Of List(Of Integer))), debes pasarle solo las colecciones del interior, las sub-listas de la lista (List(Of Integer)) y tienes que pasarselas como String.

Puedes hacerlo por ejemplo de una de estas dos maneras:

1.
Código (vbnet) [Seleccionar]
       Combos.ForEach(Sub(comb As List(Of Integer))
                          ListBox1.Items.Add(String.Join(", ", comb))
                      End Sub)


2.
Código (vbnet) [Seleccionar]

       ListBox1.Items.AddRange(
           (From comb As List(Of Integer) In Combos
            Select String.Join(", ", comb)).ToArray
        )





De todas formas habia un fallo con la colección Combos (al utilizar el método Combo.Clear se limpiaba también la referencia del Combo que habia dentro de Combos, por ende al final Combos resultaba ser una colección de listas vacías) así que te dejo esta nueva versión corregida y con el ejemplo del Listbox:

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

   ReadOnly Randomizer As New Random

   ReadOnly FixedValues As Integer() =
       Enumerable.Range(1I, 30I).ToArray ' 1 to 30

   ReadOnly RandomValues As Integer() =
       Enumerable.Range(FixedValues.First, FixedValues.Last).ToArray ' 1 to 30

   Dim Combo As List(Of Integer) = Nothing
   Dim Combos As New List(Of List(Of Integer))

   Private Sub Test() Handles MyBase.Shown

       Dim IndexCounter As Integer = FixedValues.First ' 1
       Dim LenCounter As Integer = 0I

       Const NumStep As Integer = 3I
       Const NumLen As Integer = 10I

       Do Until IndexCounter > FixedValues.Last ' IndexCounter > 30

           Combo = New List(Of Integer)

           For Num As Integer = IndexCounter To (FixedValues.Count) Step NumStep ' 1 to 30 Step 3

               Combo.Add(Num)
               LenCounter += 1I

               If LenCounter >= NumLen Then
                   Exit For
               End If

           Next ' Num

           If LenCounter < NumLen Then ' If LenCounter < 10

               For RandomNum As Integer = 1I To (NumLen - LenCounter)

                   Dim n As Integer = Randomizer.Next(RandomValues.First, RandomValues.Last)

                   Do Until Not Combo.Contains(n)
                       n = Randomizer.Next(RandomValues.First, RandomValues.Last)
                   Loop

                   Combo.Add(n)

               Next ' RandomNum

           End If ' LenCounter < NumLen

#If DEBUG Then ' #Debug
           Debug.WriteLine(String.Join(", ", Combo))
           ' Stop
#End If

           Combos.Add(Combo)
           IndexCounter += 1I
           LenCounter = 0I

       Loop ' IndexCounter >= FixedValues.Last

       ' ********
       ' Listbox:
       ' ********
       Combos.ForEach(Sub(comb As List(Of Integer))

                          ' Convierto la Lista a 'String', le añado los ceros, y añado el string formateado al Listbox.
                          ListBox1.Items.Add(String.Join(", ",
                                                         From value As String In comb
                                                         Select If(value.Length = 1I,
                                                                   value.Insert(0I, "0"c),
                                                                   value)))

                      End Sub)

   End Sub ' Test

End Class
#6679
Este código es parecido al ejemplo que mostré de como implementar una prevención de múltiples instancias, pero la diferencia de este código es que se puede especificar un máximo de instancias múltiples (en la propiedad 'SemaphID')



Código (vbnet) [Seleccionar]
' Multi-Instance Limit Example
' By Elektro

' Instructions:
' 1. Open the project properties page, goto 'Application' tab, and click in 'View application Events' button.
' 2. Copy and paste this code to replace the 'MyApplication' class contents.
' 3. Define a proper identifier for 'SemaphID' property.

Namespace My

   Partial Friend Class MyApplication

       ''' <summary>
       ''' The semaphore object used to limit the number of instances.
       ''' </summary>
       Private Semaph As Threading.Semaphore = Nothing

       ''' <summary>
       ''' Gets the current semaphore object identifier.
       ''' </summary>
       ''' <value>The current process semaphore identifier.</value>
       ''' <exception cref="System.FormatException">The specified value is not a valid GUID format.</exception>
       Private ReadOnly Property SemaphID As String
           Get

               ' Define a Golabl Unique Identifier to name the semaphore object.
               Dim Id As String = "b045ce40-2863-4ce7-a7df-8afca8214454"

               If Guid.TryParse(input:=Id, result:=New Guid) Then
                   Return Id
               Else
                   Throw New FormatException("The specified value is not in a valid GUID format.")
               End If

           End Get
       End Property

       ''' <summary>
       ''' Gets the maximum instances allowed for this process.
       ''' </summary>
       ''' <value>The maximum instances allowed for this process.</value>
       Private ReadOnly Property MaxInstances As Integer
           Get
               Return 3
           End Get
       End Property

       ''' <summary>
       ''' Determines whether the semaphore can receive a signal.
       ''' </summary>
       ''' <returns><c>true</c> if this instance [can set semaphore]; otherwise, <c>false</c>.</returns>
       Private Function CanSetSemaphore() As Boolean

           Semaph = New Threading.Semaphore(initialCount:=Me.MaxInstances,
                                            maximumCount:=Me.MaxInstances,
                                            name:=Me.SemaphID)

           Return Semaph.WaitOne(100I)

       End Function

       ''' <summary>
       ''' This occurs when the application starts, before the startup Form is created.
       ''' </summary>
       ''' <param name="sender">The source of the event.</param>
       ''' <param name="e">The <see cref="ApplicationServices.StartupEventArgs"/> instance containing the event data.</param>
       Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As ApplicationServices.StartupEventArgs) _
       Handles Me.Startup

           ' If there is more than the maximum allowed instances running with the same id then...
           If Not Me.CanSetSemaphore Then ' Prevent multi-instancing.

               MessageBox.Show("This is a limited demo, to run multiple instances please purchase the program.",
                              Application.Info.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)

               ' Cancel the application Startup to terminate the process.
               e.Cancel = True

           End If

       End Sub

       ''' <summary>
       ''' This occurs when the application shuts down.
       ''' </summary>
       ''' <param name="sender">The source of the event.</param>
       ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
       Private Sub MyApplication_Shutdown(ByVal sender As Object, ByVal e As EventArgs) _
       Handles Me.Shutdown

           If Semaph IsNot Nothing Then

               ' Free the semaphore to allow next app runs.
               Semaph.Release()
               Semaph.Close()
               Semaph = Nothing

           End If ' semaph IsNot Nothing

       End Sub

   End Class ' MyApplication

End Namespace
#6680
Un ejemplo de como añadir y usar un control WPF (no un proyecto) en Winforms, en tiempo de ejecución.

En este ejemplo uso un control simple que imita el indicador de progreso de Windows 8:



Código (vbnet) [Seleccionar]
' Example of how to add an WPF Control in a WinForms project at execution time.
' By Elektro

' Instructions:
' 1. Compile your own WPF user-control or download this one: http://www.codeproject.com/Articles/700185/Windows-Progress-Ring?msg=4884207#xx4884207xx
' 2. Add a reference to 'WindowsformsIntegration', 'PresentationFramework', 'PresentationCore', 'WindowsBase' and 'System.Xaml'.
' 3. Add a reference to our WPF library, in this example is: 'WindowsProgressRing.dll'
' 4. If the 'WindowsProgressRing.dll' user-control doesnt's load properly, set the targeting Framework to '4.5'.

#Region " Imports "

Imports System.Windows.Forms.Integration ' ElementHost

#End Region

#Region " WPFControl_TestClass "

Public Class WPFControl_TestClass

   ''' <summary>
   ''' The ElementHost instance that will host the WPF user-control.
   ''' </summary>
   Dim WPFHost As New ElementHost With {.Dock = DockStyle.Fill}

   ''' <summary>
   ''' The WPF user-control instance.
   ''' </summary>
   Dim WPFControl As New NMT.Wpf.Controls.WindowsProgressRing

   ''' <summary>
   ''' Initializes a new instance of the <see cref="WPFControl_TestClass"/> class.
   ''' </summary>
   Public Sub New()

       ' This call is required by the designer.
       InitializeComponent()

       With Me ' Set the Form properties.
           .StartPosition = FormStartPosition.CenterScreen
           .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
           .MaximizeBox = False
           .ShowIcon = False
           .BackColor = Color.Black
           .Size = New Drawing.Size(320I, 320I)

           .Controls.Add(WPFHost) ' Add the ElementHost.
       End With ' Me

       With WPFHost ' Set the ElementHost properties.
           .Width = 120I
           .Height = 120I
           WPFHost.Child = WPFControl ' Add the WPF Control.
       End With ' WPFHost

       With WPFControl ' Set the WPF Control properties.
           .Items = 60I
           .Width = 120.0R
           .Height = 120.0R
           .Speed = New Windows.Duration(TimeSpan.FromSeconds(2.5R))
           .Background = New Windows.Media.SolidColorBrush(Windows.Media.Color.FromRgb(Color.Black.R, Color.Black.G, Color.Black.B))
           .Foreground = New Windows.Media.SolidColorBrush(Windows.Media.Color.FromRgb(Color.DodgerBlue.R, Color.DodgerBlue.G, Color.DodgerBlue.B))
       End With ' WPFControl

   End Sub

End Class ' WPFControl_TestClass

#End Region