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

#5501
Cita de: Shout en 16 Marzo 2015, 04:17 AM
Esto es MUUUY hipócrita. Hablas de no creer a la tele y demás, pero tú eres el primero en defender a los conspiradores, como el JL Camacho (¿era ese el nombre?) ese, que hablaba de reptiles y no sé qué mierdas más.

Sin acritud.

Yo no defiendo a los consparanoicos, defiendo a ALGUNAS de sus hipótesis y/o teorías las cuales para mi tienen un argumento mucho más sostenible que lo que pueda salir por la boca de un político o de un presidente, pues tengo la capacidad mental cómo para estar abierto a la ÍNFIMA posibilidad de que se esté engañando a la sociedad en muchos sentidos, en muchas cosas, y muchas de ellas serían demasiado importantes como para obviarlas.

Que un tio hable sobre gilipolleces cómo una Tierra hueca (por ejemplo, yo lo considero una tontería) no significa que yo crea en todas las gilipolleces que esa persona va diciendo, y además, ¿tú te libras de haber hablado sobre tonterías en alguna que otra ocasión a lo largo de tu vida?, ¿nunca has tenido una idea que hayas querido difundir y luego te has equivocado?, revisa a ver quien es el hipócrita, porque amigo, todos somos Humanos.

PD: Me gustaría aclarar que no ignoré tu comentario, simplemente no me di cuenta hasta ahora, lo siento.

Un saludo!
#5502
Cita de: SheKeL_C$ en 16 Marzo 2015, 17:41 PMme gustaria que mi programa este a la espera hasta que un proceso determinado es llamado, una vez detectado poder modificar los argumentos que se le dan, si es que se le da alguno

¿En que lenguaje de programación lo piensas llevar a cabo?, no somos adivinos...

La tarea que pides sería extremadamente fácil de llevar a cabo con los métodos y/o componentes del lenguaje en cuestión si no fuese por que además de interceptar la llamada quieres modificar los argumentos, y eso implica técnicas de hooking, o mejor dicho API Hooking, debes hookear la pre-llamada de la función "CreateProcess" de la librería "Kernel32.dll" de la API de Windows,
en la pre-llamada a la función debes traducir/interpretar los parámetros enviados por esta función y modificarlos, donde cómo se explica la documentación oficial de la MSDN, el parámetro 'lpCommandLine' (de tipo String) contiene los argumentos commandline:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx
Nota: El primer argumento (o argumento 0) siempre debe ser la ruta del proceso.

( Quizás debas hookear también la función 'ShellExecute' de la librería 'shell32.dll' para controlar la ejecución de un proceso en ciertas circunstancias )

Existen librerías para facilitar el enrutamiento de las funciones de la API de Windows, cómo por ejemplo Microsoft Detours para C/C++, y EasyHook o Nektra Deviare para C#/VB.Net;
pero si piensas llevar a cabo la tarea sin ayuda de una librería de terceros entonces te advierto que se convertirá en una tarea horriblemente laboriosa y tediosa, y, por ejemplo en lo referente a la programación .Net requerirás un nivel medio-avanzado de conocimientos sobre el P/Invoking y el hooking, cómo Delegados, Callbacks, Marshalling, e indiferentemente del lenguaje que sea tampoco etsaría demás saber utilizar técnicas de programación asíncrónicas.

A continuación te muestro un ejempo que he desarrollado en Vb.Net utilizando la librería Deviare,
el siguiente código es un hook que se adjunta a las instancias activas del proceso "explorer.exe" y a sus procesos hijos para interceptar las llamadas a la función "CreateProcess" realizadas desde dichos procesos, si el nombre del proceso es "Notepad.exe" entonces modifico los argumentos del notepad para indicarle que cargue un archivo de texto ("C:\File.txt").

Nota: No es necesario interceptar la post-llamada de la función, pero deberías hacerlo para comprobar si hubo un error evaluando el valor de retorno de la función 'GetLastError' de la librería 'kernel32.dll" (si lo piensas hacer desde .Net entonces debes comprobar el valor de la función GetLastWin32Error de la Class 'Marshal')

Nota 2: El código de abajo es solo un ejemplo, el hook no es persistente, es decir, si reinicias el proceso Explorer.exe dejará de funcionar.

Código (vbnet) [Seleccionar]
' Nektra Deviare: "CreateProcess" hook example, By Elektro.

Imports Nektra.Deviare2
Imports System.IO

Public NotInheritable Class Form1

   Public WithEvents SpyMgr As NktSpyMgr
   Public Hook As NktHook

   ReadOnly processesToAttach As IEnumerable(Of Process) =
       Process.GetProcessesByName("explorer") '.Concat(Process.GetProcessesByName("cmd"))

   ReadOnly processToIntercept As String = "notepad.exe"
   ReadOnly processArgs As String = "C:\File.txt" ' Notepad will try to load that filepath.

   ' "CreateProcess" API reference:
   ' http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx
   Dim libName As String = "kernel32.dll"
   Dim funcName As String = "CreateProcessW" ' Unicode

   Dim hookFlags As eNktHookFlags = eNktHookFlags.flgOnlyPreCall Or
                                    eNktHookFlags.flgAutoHookChildProcess

   Private Sub Test() Handles MyBase.Load

       Me.SpyMgr = New NktSpyMgr()
       Me.SpyMgr.Initialize()

       Me.Hook = SpyMgr.CreateHook(String.Format("{0}!{1}", libName, funcName), hookFlags)

       Me.Hook.Hook(sync:=True)

       For Each proc As Process In processesToAttach
           Me.Hook.Attach(procOrId:=proc.Id, sync:=True)
       Next proc

   End Sub

   <MTAThread>
   Private Sub OnCreateProcess_Called(ByVal hook As NktHook,
                                      ByVal proc As NktProcess,
                                      ByVal callInfo As NktHookCallInfo) Handles SpyMgr.OnFunctionCalled

       Dim lpApplicationNameParam As NktParam = DirectCast(callInfo.Params(0), NktParam)
       Dim lpCommandLineParam As NktParam = DirectCast(callInfo.Params(1), NktParam)

       If Path.GetFileName(lpApplicationNameParam.Value.ToString).Equals(processToIntercept, StringComparison.OrdinalIgnoreCase) Then

           lpCommandLineParam.Value = String.Format("""{0}"" ""{1}""", lpApplicationNameParam.Value.ToString, Me.processArgs)

       End If

   End Sub

End Class


Y, si lo que quieres es evitar que un proceso invocado mediante la función "CreateProcess" se inicie, entonces debes modificar el valor de retorno (result) de la función y despues saltar la llamada, con Deviare puedes hacerlo así:
Código (vbnet) [Seleccionar]
   Private Sub OnCreateProcess_Called(ByVal hook As NktHook,
                                      ByVal proc As NktProcess,
                                      ByVal callInfo As NktHookCallInfo) Handles SpyMgr.OnFunctionCalled

       With callInfo

           If .IsPreCall Then ' Skip precall. Avoid process creation.
               .Result.Value = 1
               .SkipCall()
           End If

       End With

   End Sub


Nota: Cada función de la API de Windows tiene sus valores de retorno y debes documentarte primero para saber cómo va a afectar al SO el valor de retorno que utilices.

Saludos.
#5504
Programación C/C++ / Re: ayuda
16 Marzo 2015, 19:22 PM
Buenas.

1. Los títulos del mensaje deben ser descriptivos, está prohibido usar títulos cómo "ayudaaa"...

2. Los bloques de código deben ir en su respectiva etiqueta GeShi.

3. Las preguntas sobre C/C++ debes publicarlas en el subforo dedicado a dicho lenguaje.

Lee las reglas del foro y del foro de programación antes de postear.






Cita de: normaaaaaaaa en 16 Marzo 2015, 19:14 PM
pero me dice que no he inicializado una variable y no se porque

Aunque no manejo C/C++, el error es self-explanatory (se explica por si mismo), estás utilizando una referencia a un objeto que has declarado, pero no has inicializado, es decir, no le has asignado ningún valor por defecto, es nul,
por ende, la solución debería ser simple, revisa las variables que declaras para localizar aquella variable conflictiva a la que estés intentando acceder sin haberla inicializado primero, por ejemplo:

de:
Código (cpp) [Seleccionar]
int numParadas;
a:
Código (cpp) [Seleccionar]
int numParadas = 0;
#5505
Si una V.M. comparte la red con el equipo huésped entonces cualquier Malware con componente de red (worms) pueden comunicarse e infectar/propagarse al SO huésped.
Si una V.M. comparte discos/carpetas compartidas, entonces la V.M. está exponiendo libremente un canal de almacenamiento al que cualquier Malware puede acceder (para copiarse a si mismo, por ejemplo).

En este video se demuestra cómo una aplicación que se ejecute en el S.O. invitado (V.M.) puede comunicarse con el S.O. huésped (en este ejemplo se hace la finalidad de iniciar un proceso cualquiera cómo es la calculadora de Windows):

http://f.vimeocdn.com/p/flash/moogaloop/6.0.37/moogaloop.swf?clip_id=6595148&color=&fullscreen=1&server=vimeo.com&show_byline=1&show_portrait=0&show_title=1&controller=player2&view=moogaloop_swf&referrer=http%3A%2F%2Fsecurity.stackexchange.com%2Fquestions%2F3056%2Fhow-secure-are-virtual-machines-really-false-sense-of-security&cdn_url=http%3A%2F%2Ff.vimeocdn.com&player_url=player.vimeo.com&moogaloop_type=moogaloop

No soy experto en el diseño de malware pero, obviamente si hacemos estimaciones yo creo que estariamos hablando de un ínfimo porcentaje de desarrolladores de virus que se interesen por y sepan cómo explotar estas vulnerabilidades, ¿quizás un 0,1% de todos los virus conocidos hasta la fecha?, así que realmente yo creo que no es algo preocupante y una V.M. se puede considerar un entorno seguro para el análisis de Malware.

Saludos!
#5506
Cita de: luis456 en 16 Marzo 2015, 16:25 PMArreglo NÚMEROS = (1, 2, 3, 4, 5, 6, 10, 11, 14, 15,  54, 57, 58, 60, 63, 64, 65, 67,)

Esta seria la salida

A=01, 02, 03, 04,
B=05, 06, 10, 11,
C=14, 15,  54, 57
D=58, 60, 63, 64
E= 65, 67, 00  00 <---aca me las arreglo con un pedazo de código tuyo :) para completar

Eso es una simple partición, que no concuerda en absoluto con las colecciones que estás generando en el primer código que mostraste, donde utilizas el operador Mod para filtrar la secuencia y, claro está, da un resultado muy diferente al que has hecho referencia ahora:

Citar
Código (vbnet) [Seleccionar]
   Dim evensQuery = From num In numbers
                       Where num Mod 2 = 0
                       Select num

       Dim ll = From num In numbers
              Where num Mod 2 = 1
              Select num

       Dim ll1 = From num In numbers
              Where num Mod 3 = 0
              Select num

¿Entonces?.




En el primer caso, es decir, partir la colección en colecciones de 4 partes (cosa que ya te mostré cómo hacerlo) y rellenar con "ceros" los elementos restantes de la última "parte", es tan sencillo cómo esto:

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

   Private Sub Test() Handles MyBase.Shown

       Dim values As IEnumerable(Of Integer) =
           {
               1, 2, 3, 4,
               5, 6, 10, 11,
               14, 15, 54, 57,
               58, 60, 63, 64,
               65, 67
           }

       Dim splits As IEnumerable(Of IEnumerable(Of Integer)) =
           SplitIntoParts(collection:=values, amount:=4,
                          fillEmpty:=True)

       Me.ListBox1.Items.AddRange(splits(0).Cast(Of Object).ToArray)
       Me.ListBox2.Items.AddRange(splits(1).Cast(Of Object).ToArray)
       Me.ListBox3.Items.AddRange(splits(2).Cast(Of Object).ToArray)

   End Sub

   ''' <remarks>
   ''' *****************************************************************
   ''' Snippet Title: Split Collection Into Parts
   ''' Code's Author: Elektro
   ''' Date Modified: 16-March-2015
   ''' Usage Example:
   ''' Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
   ''' Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = SplitColIntoParts(mainCol, amount:=4, fillEmpty:=True)
   ''' splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
   '''                                 Debug.WriteLine(String.Join(", ", col))
   '''                             End Sub)
   ''' *****************************************************************
   ''' </remarks>
   ''' <summary>
   ''' Splits an <see cref="IEnumerable(Of T)"/> into the specified amount of elements.
   ''' </summary>
   ''' <typeparam name="T"></typeparam>
   ''' <param name="collection">The collection to split.</param>
   ''' <param name="amount">The target elements amount.</param>
   ''' <param name="fillEmpty">If set to <c>true</c>, generate empty elements to fill the last secuence's part amount.</param>
   ''' <returns>IEnumerable(Of IEnumerable(Of T)).</returns>
   Public Shared Function SplitIntoParts(Of T)(ByVal collection As IEnumerable(Of T),
                                               ByVal amount As Integer,
                                               ByVal fillEmpty As Boolean) As IEnumerable(Of IEnumerable(Of T))

       Dim newCol As IEnumerable(Of List(Of T)) =
           (From index As Integer
           In Enumerable.Range(0, CInt(Math.Ceiling(collection.Count() / amount)))
           Select collection.Skip(index * amount).Take(amount).ToList).ToList

       If fillEmpty Then

           Do Until newCol.Last.Count = amount
               newCol.Last.Add(Nothing)
           Loop

       End If

       Return newCol

   End Function

End Class


EDITO:
Una actualización de la función:

Código (vbnet) [Seleccionar]
   Public Shared Function SplitIntoParts(Of T)(ByVal collection As IEnumerable(Of T),
                                               ByVal amount As Integer,
                                               ByVal fillEmpty As Boolean) As IEnumerable(Of IEnumerable(Of T))

       Return From index As Integer In Enumerable.Range(0, CInt(Math.Ceiling(collection.Count() / amount)))
              Select If(Not fillEmpty,
                        collection.Skip(index * amount).Take(amount),
                        If((collection.Count() - (index * amount)) >= amount,
                           collection.Skip(index * amount).Take(amount),
                           collection.Skip(index * amount).Take(amount).
                                                           Concat(From i As Integer
                                                                  In Enumerable.Range(0, amount - (collection.Count() - (index * amount)))
                                                                  Select DirectCast(Nothing, T))))

   End Function


Saludos
#5507
Imagino que cuando dices que quieres automatizar la tarea pretendes hacerlo desde .Net,
No se si esto te servirá por que no estoy muy seguro de lo si esto es lo que realmente buscas, pero ayer me puse a desarrollar un laaaargo Snippet que quizás te sería de utilidad,
la finalidad del siguiente código es crear y gestionar una tabla de recursos .Net, es decir, un archivo .ResX, que no sería más que un archivo XML donde sus nodos contendrían los datos de los recursos.
El único inconveniente es que al ser un archivo de texto plano, los datos serializados de un recurso binario ocuparían más de lo que ocuparía realmente ese archivo binario (al reconstruirlo), espero que se me entienda, jeje.

Una vez hayas creado el archivo .resx y le hayas añadido los recursos que quieras, solo tendrías que embedir este archivo ResX, al ensamblado.

Te muestro un multi-ejemplo de uso con varios tipos de recursos, aunque está escrito en VB.Net y sino recuerdo mal tú experiencia está basada en C#, pero el uso de este código es sencillo, genérico e intuitivo (o eso pretendí conseguir), no te costaría traducirlo a C#:

Código (vbnet) [Seleccionar]
Imports System.IO
Imports System.Text

Public Class Form1

   Private Sub Test() Handles MyBase.Shown

       Dim resX As New ResXManager(Path.Combine(Application.StartupPath, "MyResources.resx"))
       With resX

           ' Create or replace the ResX file.
           .Create(replace:=True)

           ' Add a string resource.
           .AddResource(Of String)("String Resource", "Hello World!", "String Comment")
           ' Add a bitmap resource.
           .AddResource(Of Bitmap)("Bitmap Resource", SystemIcons.Information.ToBitmap, "Bitmap Comment")
           ' Add a binary resource.
           .AddResource(Of Byte())("Binary Resource", File.ReadAllBytes("C:\file.mp3"), "Binary Comment")

       End With

       ' *******************************************************************************************************

       ' Get the string resource.
       Dim stringResource As ResXManager.Resource(Of String) =
           resX.FindResource(Of String)("String Resource", StringComparison.OrdinalIgnoreCase)

       ' Get the bitmap resource.
       Dim bitmapResource As ResXManager.Resource(Of Bitmap) =
           resX.FindResource(Of Bitmap)("Bitmap Resource", StringComparison.OrdinalIgnoreCase)

       ' Get the binary resource.
       Dim binaryResource As ResXManager.Resource(Of Byte()) =
           resX.FindResource(Of Byte())("Binary Resource", StringComparison.OrdinalIgnoreCase)

       ' *******************************************************************************************************

       ' Get the string data.
       Dim stringData As String = stringResource.Data

       ' Get the bitmap data.
       Dim bitmapData As Bitmap = bitmapResource.Data

       ' Get the binary data.
       Dim binaryData As Byte() = binaryResource.Data

       ' *******************************************************************************************************

       ' Get all the resources at once.
       Dim resources As IEnumerable(Of ResXManager.Resource) = resX.Resources

       ' Get all the resources of specific Type at once.
       Dim stringResources As IEnumerable(Of ResXManager.Resource(Of String)) = resX.FindResources(Of String)()

       ' *******************************************************************************************************

       ' Get all the resource datas at once from Resource collection.
       Dim resourceDatas As IEnumerable(Of Object) =
           From res As ResXManager.Resource In resX.Resources
           Select res.Data

       ' Get all the resource datas of specific Type at once from Resource collection.
       Dim stringResourceDatas As IEnumerable(Of String) =
           From res As ResXManager.Resource In resX.Resources
           Where res.Type Is GetType(String)
           Select DirectCast(res.Data, String)

       ' *******************************************************************************************************

       ' Treat the string resource as you like.
       MessageBox.Show(stringData, String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information)

       ' Treat the bitmap resource as you like.
       Me.Icon = Icon.FromHandle(bitmapData.GetHicon)

       ' Treat the binary resource as you like.
       File.WriteAllBytes("C:\new file.mp3", binaryData)

       ' *******************************************************************************************************

       ' Iterate all the resources.
       For Each res As ResXManager.Resource In resX.Resources

           Dim sb As New StringBuilder

           sb.AppendLine(String.Format("Name...: {0}", res.Name))
           sb.AppendLine(String.Format("Comment: {0}", res.Comment))
           sb.AppendLine(String.Format("Type...: {0}", res.Type.ToString))
           sb.AppendLine(String.Format("Data...: {0}", res.Data.ToString))

           MsgBox(sb.ToString)
       Next

       ' Iterate all the resources of specific Type.
       For Each res As ResXManager.Resource(Of String) In resX.FindResources(Of String)()

           Dim sb As New StringBuilder

           sb.AppendLine(String.Format("Name...: {0}", res.Name))
           sb.AppendLine(String.Format("Comment: {0}", res.Comment))
           sb.AppendLine(String.Format("Type...: {0}", res.Type.ToString))
           sb.AppendLine(String.Format("Data...: {0}", res.Data.ToString))

           MsgBox(sb.ToString)
       Next

       ' *******************************************************************************************************

       ' Remove a resource.
       resX.RemoveResource("Binary Resource")

       '  GC.Collect()

   End Sub

End Class


Este es el código fuente, que obviamente no sería necesario traducirlo a C#, ya que puedes compilarlo a una librería.dll externa o "interna":

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Elektro
' Modified : 16-March-2015
' ***********************************************************************
' <copyright file="ResXManager.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Option Statements "

Option Strict On
Option Explicit On
Option Infer Off

#End Region

#Region " Usage Examples "

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.IO
Imports System.Resources

#End Region

''' <summary>
''' Manages a .Net managed resource file.
''' </summary>
Public NotInheritable Class ResXManager

#Region " Properties "

   ''' <summary>
   ''' Gets the .Net managed resource file path.
   ''' </summary>
   ''' <value>The .Net managed resource filepath.</value>
   Public ReadOnly Property FilePath As String
       Get
           Return Me.filePath1
       End Get
   End Property
   ''' <summary>
   ''' The .Net managed resource file path.
   ''' </summary>
   Private ReadOnly filePath1 As String

   ''' <summary>
   ''' Gets the resources contained in the .Net managed resource file.
   ''' </summary>
   ''' <value>The resources.</value>
   Public ReadOnly Property Resources As IEnumerable(Of Resource)
       Get
           Return GetResources()
       End Get
   End Property

#End Region

#Region " Types "

#Region " Resource "

   ''' <summary>
   ''' Defines a resource of a .Net managed resource file.
   ''' </summary>
   <Serializable>
   Public NotInheritable Class Resource

#Region " Properties "

       ''' <summary>
       ''' Gets the resource name.
       ''' </summary>
       ''' <value>The resource name.</value>
       Public ReadOnly Property Name As String
           Get
               Return Me.name1
           End Get
       End Property
       Private ReadOnly name1 As String

       ''' <summary>
       ''' Gets the resource data.
       ''' </summary>
       ''' <value>The resource data.</value>
       Public ReadOnly Property Data As Object
           Get
               Return Me.data1
           End Get
       End Property
       Private ReadOnly data1 As Object

       ''' <summary>
       ''' Gets the resource type.
       ''' </summary>
       ''' <value>The resource type.</value>
       Public ReadOnly Property Type As Type
           Get
               Return Data.GetType
           End Get
       End Property

       ''' <summary>
       ''' Gets the resource comment.
       ''' </summary>
       ''' <value>The resource comment.</value>
       Public ReadOnly Property Comment As String
           Get
               Return comment1
           End Get
       End Property
       Private ReadOnly comment1 As String

       ''' <summary>
       ''' Represents a <see cref="Resource"/> instance that is <c>Nothing</c>.
       ''' </summary>
       ''' <value><c>Nothing</c></value>
       <EditorBrowsable(EditorBrowsableState.Advanced)>
       Public Shared ReadOnly Property Empty As Resource
           Get
               Return Nothing
           End Get
       End Property

#End Region

#Region " Constructors "

       ''' <summary>
       ''' Initializes a new instance of the <see cref="Resource"/> class.
       ''' </summary>
       ''' <param name="name">The resource name.</param>
       ''' <param name="data">The resource data.</param>
       ''' <param name="comment">The resource comment.</param>
       Public Sub New(ByVal name As String,
                      ByVal data As Object,
                      ByVal comment As String)

           Me.name1 = name
           Me.data1 = data
           Me.comment1 = comment

       End Sub

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

#End Region

#Region " Hidden Methods "

       ''' <summary>
       ''' Determines whether the specified System.Object instances are considered equal.
       ''' </summary>
       <EditorBrowsable(EditorBrowsableState.Never)>
       Public Shadows Function Equals(ByVal obj As Object) As Boolean
           Return MyBase.Equals(obj)
       End Function

       ''' <summary>
       ''' Serves as a hash function for a particular type.
       ''' </summary>
       <EditorBrowsable(EditorBrowsableState.Never)>
       Public Shadows Function GetHashCode() As Integer
           Return MyBase.GetHashCode
       End Function

       ''' <summary>
       ''' Gets the System.Type of the current instance.
       ''' </summary>
       ''' <returns>The exact runtime type of the current instance.</returns>
       <EditorBrowsable(EditorBrowsableState.Never)>
       Public Shadows Function [GetType]() As Type
           Return MyBase.GetType
       End Function

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

#End Region

   End Class

#End Region

#Region " Resource(Of T) "

   ''' <summary>
   ''' Defines a resource of a .Net managed resource file.
   ''' </summary>
   <Serializable>
   Public NotInheritable Class Resource(Of T)

#Region " Properties "

       ''' <summary>
       ''' Gets the resource name.
       ''' </summary>
       ''' <value>The resource name.</value>
       Public ReadOnly Property Name As String
           Get
               Return Me.name1
           End Get
       End Property
       Private ReadOnly name1 As String

       ''' <summary>
       ''' Gets the resource data.
       ''' </summary>
       ''' <value>The resource data.</value>
       Public ReadOnly Property Data As T
           Get
               Return Me.data1
           End Get
       End Property
       Private ReadOnly data1 As T

       ''' <summary>
       ''' Gets the resource type.
       ''' </summary>
       ''' <value>The resource type.</value>
       Public ReadOnly Property Type As Type
           Get
               Return GetType(T)
           End Get
       End Property

       ''' <summary>
       ''' Gets the resource comment.
       ''' </summary>
       ''' <value>The resource comment.</value>
       Public ReadOnly Property Comment As String
           Get
               Return comment1
           End Get
       End Property
       Private ReadOnly comment1 As String

#End Region

#Region " Constructors "

       ''' <summary>
       ''' Initializes a new instance of the <see cref="Resource(Of T)"/> class.
       ''' </summary>
       ''' <param name="name">The resource name.</param>
       ''' <param name="data">The resource data.</param>
       ''' <param name="comment">The resource comment.</param>
       Public Sub New(ByVal name As String,
                      ByVal data As T,
                      ByVal comment As String)

           Me.name1 = name
           Me.data1 = data
           Me.comment1 = comment

       End Sub

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

#End Region

#Region " Hidden Methods "

       ''' <summary>
       ''' Determines whether the specified System.Object instances are considered equal.
       ''' </summary>
       <EditorBrowsable(EditorBrowsableState.Never)>
       Public Shadows Function Equals(ByVal obj As Object) As Boolean
           Return MyBase.Equals(obj)
       End Function

       ''' <summary>
       ''' Serves as a hash function for a particular type.
       ''' </summary>
       <EditorBrowsable(EditorBrowsableState.Never)>
       Public Shadows Function GetHashCode() As Integer
           Return MyBase.GetHashCode
       End Function

       ''' <summary>
       ''' Gets the System.Type of the current instance.
       ''' </summary>
       ''' <returns>The exact runtime type of the current instance.</returns>
       <EditorBrowsable(EditorBrowsableState.Never)>
       Public Shadows Function [GetType]() As Type
           Return MyBase.GetType
       End Function

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

#End Region

   End Class

#End Region

#End Region

#Region " Constructors "

   ''' <summary>
   ''' Initializes a new instance of the <see cref="ResXManager"/> class.
   ''' </summary>
   ''' <param name="resxFilePath">The .Net managed resource filepath.</param>
   Public Sub New(ByVal resxFilePath As String)
       Me.filePath1 = resxFilePath
   End Sub

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

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Creates the .Net managed resource file.
   ''' </summary>
   ''' <param name="replace">if set to <c>true</c>, replaces any existent file.</param>
   ''' <exception cref="System.Exception"></exception>
   Public Sub Create(Optional ByVal replace As Boolean = False)

       If Not replace AndAlso File.Exists(Me.filePath1) Then
           Throw New Exception(String.Format("Resource file already exists: {0}", Me.filePath1))
           Exit Sub
       End If

       Dim resXWritter As ResXResourceWriter = Nothing
       Try
           resXWritter = New ResXResourceWriter(Me.filePath1)
           Using resXWritter
               resXWritter.Generate()
           End Using

       Catch ex As Exception
           Throw

       Finally
           If resXWritter IsNot Nothing Then
               resXWritter.Close()
           End If

       End Try

   End Sub

   ''' <summary>
   ''' Adds a resource into the .Net managed resource file.
   ''' </summary>
   ''' <param name="name">The resource name.</param>
   ''' <param name="data">The resource data.</param>
   ''' <param name="comment">The resource comment.</param>
   ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
   ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
   Public Sub AddResource(ByVal name As String,
                          ByVal data As Object,
                          Optional ByVal comment As String = Nothing)

       Me.AddResource(replace:=False, name:=name, data:=data, comment:=comment)

   End Sub

   ''' <summary>
   ''' Adds a specified resource of the specified type into the .Net managed resource file.
   ''' </summary>
   ''' <typeparam name="T"></typeparam>
   ''' <param name="name">The resource name.</param>
   ''' <param name="data">The resource data.</param>
   ''' <param name="comment">The resource comment.</param>
   ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
   ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
   Public Sub AddResource(Of T)(ByVal name As String,
                                ByVal data As T,
                                Optional ByVal comment As String = Nothing)

       Me.AddResource(replace:=False, name:=name, data:=data, comment:=comment)

   End Sub

   ''' <summary>
   ''' Replaces a resource by the specified name inside the .Net managed resource file.
   ''' </summary>
   ''' <param name="name">The resource name.</param>
   ''' <param name="data">The resource data.</param>
   ''' <param name="comment">The resource comment.</param>
   ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
   ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
   Public Sub ReplaceResource(ByVal name As String,
                              ByVal data As Object,
                              Optional ByVal comment As String = Nothing)

       Me.AddResource(replace:=True, name:=name, data:=data, comment:=comment)

   End Sub

   ''' <summary>
   ''' Replaces a resource by the specified name of the specified type inside the .Net managed resource file.
   ''' </summary>
   ''' <typeparam name="T"></typeparam>
   ''' <param name="name">The resource name.</param>
   ''' <param name="data">The resource data.</param>
   ''' <param name="comment">The resource comment.</param>
   ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
   ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
   Public Sub ReplaceResource(Of T)(ByVal name As String,
                                    ByVal data As T,
                                    Optional ByVal comment As String = Nothing)

       Me.AddResource(replace:=True, name:=name, data:=data, comment:=comment)

   End Sub

   ''' <summary>
   ''' Finds a resource by the specified name of specified type inside the .Net managed resource file.
   ''' </summary>
   ''' <typeparam name="T"></typeparam>
   ''' <param name="name">The resource name.</param>
   ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param>
   ''' <returns>The resource.</returns>
   ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
   ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception>
   ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception>
   Public Function FindResource(Of T)(ByVal name As String,
                                      Optional ByVal stringComparison As StringComparison =
                                                     StringComparison.OrdinalIgnoreCase) As Resource(Of T)

       If Not File.Exists(Me.filePath1) Then
           Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
           Exit Function
       End If

       ' Read the ResX file.
       Dim resX As ResXResourceReader = Nothing
       Dim res As Resource(Of T) = Nothing
       Try
           resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
           Using resX

               For Each entry As DictionaryEntry In resX

                   If entry.Key.ToString.Equals(name, stringComparison) Then

                       Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)

                       res = New Resource(Of T)(name:=node.Name,
                                                data:=DirectCast(node.GetValue(DirectCast(Nothing, ITypeResolutionService)), T),
                                                comment:=node.Comment)
                       Exit For

                   End If

               Next entry

           End Using ' resX

           Return res

       Catch ex As Exception
           Throw

       Finally
           If resX IsNot Nothing Then
               resX.Close()
           End If

       End Try

   End Function

   ''' <summary>
   ''' Finds a resource by the specified name inside the .Net managed resource file.
   ''' </summary>
   ''' <param name="name">The resource name.</param>
   ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param>
   ''' <returns>The resource.</returns>
   ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
   ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception>
   ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception>
   Public Function FindResource(ByVal name As String,
                                Optional ByVal stringComparison As StringComparison =
                                               StringComparison.OrdinalIgnoreCase) As Resource

       If Not File.Exists(Me.filePath1) Then
           Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
           Exit Function
       End If

       ' Read the ResX file.
       Dim resX As ResXResourceReader = Nothing
       Dim res As Resource = Nothing
       Try
           resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
           Using resX

               For Each entry As DictionaryEntry In resX

                   If entry.Key.ToString.Equals(name, stringComparison) Then

                       Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)

                       res = New Resource(name:=node.Name,
                                          data:=node.GetValue(DirectCast(Nothing, ITypeResolutionService)),
                                          comment:=node.Comment)
                       Exit For

                   End If

               Next entry

           End Using ' resX

           Return res

       Catch ex As Exception
           Throw

       Finally
           If resX IsNot Nothing Then
               resX.Close()
           End If

       End Try

   End Function

   ''' <summary>
   ''' Finds the resources of the specified type inside the .Net managed resource file.
   ''' </summary>
   ''' <typeparam name="T"></typeparam>
   ''' <returns>The resource.</returns>
   ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
   ''' <exception cref="System.ArgumentException">Resource with the specified name is not found.;name</exception>
   ''' <exception cref="System.ArgumentException">The specified Type differs from the resource Type.;T</exception>
   Public Iterator Function FindResources(Of T)() As IEnumerable(Of Resource(Of T))

       If Not File.Exists(Me.filePath1) Then
           Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
           Exit Function
       End If

       ' Read the ResX file.
       Dim resX As ResXResourceReader = Nothing
       Try
           resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
           Using resX

               For Each entry As DictionaryEntry In resX

                   Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)

                   If node.GetValue(DirectCast(Nothing, ITypeResolutionService)).GetType Is GetType(T) Then

                       Yield New Resource(Of T)(name:=node.Name,
                                          data:=DirectCast(node.GetValue(DirectCast(Nothing, ITypeResolutionService)), T),
                                          comment:=node.Comment)

                   End If

               Next entry

           End Using ' resX

       Catch ex As Exception
           Throw

       Finally
           If resX IsNot Nothing Then
               resX.Close()
           End If

       End Try

   End Function

   ''' <summary>
   ''' Removes a resource by the specified name from the .Net managed resource file.
   ''' </summary>
   ''' <param name="name">The resource name.</param>
   ''' <param name="stringComparison">The <see cref="StringComparison"/> to compare the resource name.</param>
   ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
   ''' <exception cref="System.ArgumentException">Any resource found matching the specified name.;name</exception>
   Public Sub RemoveResource(ByVal name As String,
                             Optional ByVal stringComparison As StringComparison =
                                            StringComparison.OrdinalIgnoreCase)

       If Not File.Exists(Me.filePath1) Then
           Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
           Exit Sub
       End If

       If Me.FindResource(name, stringComparison) Is Nothing Then
           Throw New ArgumentException("Any resource found matching the specified name.", "name")
           Exit Sub
       End If

       Dim resources As New List(Of ResXDataNode)
       Dim resX As ResXResourceReader = Nothing
       Dim resXWritter As ResXResourceWriter = Nothing

       Try
           resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
           Using resX

               For Each entry As DictionaryEntry In resX

                   If Not entry.Key.ToString.Equals(name, stringComparison) Then

                       Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
                       resources.Add(New ResXDataNode(name:=node.Name, value:=node.GetValue(DirectCast(Nothing, ITypeResolutionService))) With {.Comment = node.Comment})

                   End If

               Next entry

           End Using

           ' Add the resource in the ResX file.
           ' Note: This will replace the current ResX file.
           resXWritter = New ResXResourceWriter(Me.filePath1)
           Using resXWritter

               ' Add the retrieved resources into the ResX file.
               If resources IsNot Nothing Then
                   For Each resourceItem As ResXDataNode In resources
                       resXWritter.AddResource(resourceItem)
                   Next resourceItem
               End If

               resXWritter.Generate()

           End Using ' resXWritter

       Catch ex As Exception
           Throw

       Finally
           If resX IsNot Nothing Then
               resX.Close()
           End If

           If resXWritter IsNot Nothing Then
               resXWritter.Close()
           End If

           resources.Clear()

       End Try

   End Sub

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Adds or replaces a resource into the .Net managed resource file.
   ''' </summary>
   ''' <param name="replace">if set to <c>true</c>, the resource will be replaced.</param>
   ''' <param name="name">The resource name.</param>
   ''' <param name="data">The resource data.</param>
   ''' <param name="comment">The resource comment.</param>
   ''' <exception cref="System.IO.FileNotFoundException">Resource file not found.</exception>
   ''' <exception cref="System.ArgumentException">A resource with the same name already exists in the table.;name</exception>
   Private Sub AddResource(ByVal replace As Boolean,
                           ByVal name As String,
                           ByVal data As Object,
                           ByVal comment As String)

       If Not File.Exists(Me.filePath1) Then
           Throw New FileNotFoundException("Resource file not found.", Me.filePath1)
           Exit Sub
       End If

       Dim resources As New List(Of ResXDataNode)
       Dim resX As ResXResourceReader = Nothing
       Dim resXWritter As ResXResourceWriter = Nothing

       Try
           resX = New ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}
           Using resX

               For Each entry As DictionaryEntry In resX

                   If Not replace AndAlso entry.Key.ToString.Equals(name, StringComparison.OrdinalIgnoreCase) Then
                       Throw New ArgumentException("A resource with the same name already exists in the table.", "name")

                   Else
                       Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)
                       resources.Add(New ResXDataNode(name:=node.Name, value:=node.GetValue(DirectCast(Nothing, ITypeResolutionService))) With {.Comment = node.Comment})

                   End If

               Next entry

           End Using

           ' Add the resource in the ResX file.
           ' Note: This will replace the current ResX file.
           resXWritter = New ResXResourceWriter(Me.filePath1)
           Using resXWritter

               ' Add the retrieved resources into the ResX file.
               If resources IsNot Nothing Then
                   For Each resourceItem As ResXDataNode In resources
                       resXWritter.AddResource(resourceItem)
                   Next resourceItem
               End If

               ' Add the specified resource into the ResX file.
               resXWritter.AddResource(New ResXDataNode(name, data) With {.Name = name, .Comment = comment})
               resXWritter.Generate()

           End Using ' resXWritter

       Catch ex As Exception
           Throw

       Finally
           If resX IsNot Nothing Then
               resX.Close()
           End If

           If resXWritter IsNot Nothing Then
               resXWritter.Close()
           End If

           resources.Clear()

       End Try

   End Sub

   ''' <summary>
   ''' Gets all the resources contained in the .Net managed resource file.
   ''' </summary>
   ''' <returns>IEnumerable(Of Resource).</returns>
   Private Iterator Function GetResources() As IEnumerable(Of Resource)

       ' Read the ResX file.
       Using resX As New Resources.ResXResourceReader(Me.filePath1) With {.UseResXDataNodes = True}

           For Each entry As DictionaryEntry In resX

               Dim node As ResXDataNode = CType(entry.Value, ResXDataNode)

               Yield New Resource(name:=node.Name,
                                  data:=node.GetValue(DirectCast(Nothing, ITypeResolutionService)),
                                  comment:=node.Comment)

           Next entry

       End Using ' resX

   End Function

#End Region

#Region " Hidden Methods "

   ''' <summary>
   ''' Determines whether the specified System.Object instances are considered equal.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Function Equals(ByVal obj As Object) As Boolean
       Return MyBase.Equals(obj)
   End Function

   ''' <summary>
   ''' Serves as a hash function for a particular type.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Function GetHashCode() As Integer
       Return MyBase.GetHashCode
   End Function

   ''' <summary>
   ''' Gets the System.Type of the current instance.
   ''' </summary>
   ''' <returns>The exact runtime type of the current instance.</returns>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Function [GetType]() As Type
       Return MyBase.GetType
   End Function

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

#End Region

End Class


Saludos!
#5508
Cita de: luis456 en 16 Marzo 2015, 13:02 PMa medida que alargo los números estos se quedan cortos ;(

¿Qué?.

Compila el código que has mostrado, mira el resultado que da (2,4,6,10 | 1,3,5,11 | 3,6,15,54), y explica que resultado sería el que esperas obtener.

Saludos
#5509
Hay varias formas, creando una tarea del sistema específica para iniciar una aplicación al iniciar sesión, añadir un valor a la clave de registro que administra las aplicaciones que se inician al iniciar sesión, o añadiendo aplicaciones/accesos directos en el directorio Startup, que eso parece ser lo que quieres:

"C:\Users\Nombre\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

PD: Si quieres conocer más detalles sobre las otras alternativas, haz una búsqueda en Google, la información abunda.

Saludos