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

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 2 Visitantes están viendo este tema.
Páginas: 1 ... 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 [46] 47 48 49 50 51 52 53 54 55 56 57 58 59 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 526,931 veces)
OscarCadenas_91

Desconectado Desconectado

Mensajes: 27


Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #450 en: 9 Febrero 2015, 09:12 am »

que guay todo lo que aportas vale oro.

Gracias por compartir tus codigos ;-) ;-)


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #451 en: 14 Febrero 2015, 17:12 pm »

Tras analizar diversos enfoques de iteradores y paralelismo para optimizar la manera de buscar archivos/carpetas, y aunque al final he preferido no programar las funciones de manera asíncrona, les presento el método definitivo (bueno, o casi xD) para buscar archivos/directorios de manera sencilla, personalizada, omitiendo y/o controlando errores de permisos de usuario (eso si, de forma básica, quien quiera puede añadirle eventos para un mayor control), y realizando una búsqueda muy, muy rápida al dividir el trabajo en varios threads, de esta manera disminuirán el tiempo de ejecución hasta un 400% en las búsquedas de archivos por ejemplo sería muy útil en aplicaciones de tipo USB-Stealer, donde es primordial la rápidez del algoritmo sin dejar de lado la eficiencia del mismo.

Modo de empleo:

Código
  1. Dim filePaths As List(Of String) = FileDirSearcher.GetFilePaths("C:\Windows\System32", SearchOption.AllDirectories).ToList
  2. Dim dirPaths As List(Of String) = FileDirSearcher.GetDirPaths("C:\Windows\System32", SearchOption.AllDirectories).ToList

o:
Código
  1. Dim files As List(Of FileInfo) = FileDirSearcher.GetFiles("C:\Windows\System32", SearchOption.AllDirectories).ToList
  2. Dim dirs As List(Of DirectoryInfo) = FileDirSearcher.GetDirs("C:\Windows\System32", SearchOption.AllDirectories).ToList

o:
Código
  1. Dim files As IEnumerable(Of FileInfo) = FileDirSearcher.GetFiles(dirPath:="C:\Windows\System32",
  2.                                                                 searchOption:=SearchOption.TopDirectoryOnly,
  3.                                                                 fileNamePatterns:={"*"},
  4.                                                                 fileExtPatterns:={"*.dll", "*.exe"},
  5.                                                                 ignoreCase:=True,
  6.                                                                 throwOnError:=True)
  7.  
  8. Dim dirs As IEnumerable(Of DirectoryInfo) = FileDirSearcher.GetDirs(dirPath:="C:\Windows\System32",
  9.                                                                    searchOption:=SearchOption.TopDirectoryOnly,
  10.                                                                    dirPathPatterns:={"*"},
  11.                                                                    dirNamePatterns:={"*Microsoft*"},
  12.                                                                    ignoreCase:=True,
  13.                                                                    throwOnError:=True)
  14.  

Source: http://pastebin.com/yrcvG7LP

EDITO: Versión anterior del código fuente de este Snippet (no tiene ninguna mejora implementada), por si quieren comparar los tiempos de espera de búsqueda: http://pastebin.com/Wg5SHdmS


« Última modificación: 14 Febrero 2015, 17:24 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #452 en: 14 Febrero 2015, 20:30 pm »

Esto es una versión "reducida" de la class para buscar archivos/directorios. El funcionamiento es el mismo pero internamente trabaja de manera ligeramente distinta, simplemente lo he estructurado de otra forma más óptima para eliminar toda la repetición de código posible y así hacer el entendimiento del código más ameno, los resultados son los mismos.

Nota: Si alquien quiere comparar este código con algún otro algoritmo (que de seguro los hay mejores) para hacer algún tipo de profilling de I/O o del rendimiento de memoria entonces no se vayan a asustar por el consumo de memoria al recojer +100k de archivos, es el GarbageCollector de .Net haciendo de las suyas... lo pueden invokar manualmente (GC.Collect) y desaparecerá todo ese consumo ficticio de RAM.

Espero que a alguien le sirva el code :):

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 14-February-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Usage Examples "
  7.  
  8. ' he eliminado esto por el límite de caracteres del foro
  9.  
  10. #End Region
  11.  
  12. #Region " Option Statements "
  13.  
  14. Option Explicit On
  15. Option Strict On
  16. Option Infer Off
  17.  
  18. #End Region
  19.  
  20. #Region " Imports "
  21.  
  22. Imports System.IO
  23. Imports System.Collections.Concurrent
  24. Imports System.Threading.Tasks
  25.  
  26. #End Region
  27.  
  28. #Region " File Dir Searcher "
  29.  
  30. ''' <summary>
  31. ''' Searchs for files and directories.
  32. ''' </summary>
  33. Public NotInheritable Class FileDirSearcher
  34.  
  35. #Region " Public Methods "
  36.  
  37.    ''' <summary>
  38.    ''' Gets the files those matches the criteria inside the specified directory and/or sub-directories.
  39.    ''' </summary>
  40.    ''' <param name="dirPath">The root directory path to search for files.</param>
  41.    ''' <param name="searchOption">The searching mode.</param>
  42.    ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  43.    ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  44.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  45.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  46.    ''' <returns>An <see cref="IEnumerable(Of FileInfo)"/> instance containing the files information.</returns>
  47.    ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  48.    Public Shared Function GetFiles(ByVal dirPath As String,
  49.                                    ByVal searchOption As SearchOption,
  50.                                    Optional ByVal fileNamePatterns As IEnumerable(Of String) = Nothing,
  51.                                    Optional ByVal fileExtPatterns As IEnumerable(Of String) = Nothing,
  52.                                    Optional ByVal ignoreCase As Boolean = True,
  53.                                    Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of FileInfo)
  54.  
  55.        ' Analyze and resolve path problems. (eg. 'C:' -> 'C:\')
  56.        AnalyzePath(dirPath)
  57.  
  58.        ' Analyze the passed arguments.
  59.        AnalyzeArgs(dirPath, searchOption)
  60.  
  61.        ' Get and return the files.
  62.        Dim queue As New ConcurrentQueue(Of FileInfo)
  63.        CollectFiles(queue, dirPath, searchOption, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  64.        Return queue.AsEnumerable
  65.  
  66.    End Function
  67.  
  68.    ''' <summary>
  69.    ''' Gets the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  70.    ''' </summary>
  71.    ''' <param name="dirPath">The root directory path to search for files.</param>
  72.    ''' <param name="searchOption">The searching mode.</param>
  73.    ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  74.    ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  75.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  76.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  77.    ''' <returns>An <see cref="IEnumerable(Of String)"/> instance containing the filepaths.</returns>
  78.    ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  79.    Public Shared Function GetFilePaths(ByVal dirPath As String,
  80.                                        ByVal searchOption As SearchOption,
  81.                                        Optional ByVal fileNamePatterns As IEnumerable(Of String) = Nothing,
  82.                                        Optional ByVal fileExtPatterns As IEnumerable(Of String) = Nothing,
  83.                                        Optional ByVal ignoreCase As Boolean = True,
  84.                                        Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of String)
  85.  
  86.        ' Analyze and resolve path problems. (eg. 'C:' -> 'C:\')
  87.        AnalyzePath(dirPath)
  88.  
  89.        ' Analyze the passed arguments.
  90.        AnalyzeArgs(dirPath, searchOption)
  91.  
  92.        ' Get and return the filepaths.
  93.        Dim queue As New ConcurrentQueue(Of String)
  94.        CollectFilePaths(queue, dirPath, searchOption, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  95.        Return queue.AsEnumerable
  96.  
  97.    End Function
  98.  
  99.    ''' <summary>
  100.    ''' Gets the directories those matches the criteria inside the specified directory and/or sub-directories.
  101.    ''' </summary>
  102.    ''' <param name="dirPath">The root directory path to search for directories.</param>
  103.    ''' <param name="searchOption">The searching mode.</param>
  104.    ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  105.    ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  106.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  107.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to directory.</param>
  108.    ''' <returns>An <see cref="IEnumerable(Of DirectoryInfo)"/> instance containing the dirrectories information.</returns>
  109.    ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  110.    Public Shared Function GetDirs(ByVal dirPath As String,
  111.                                   ByVal searchOption As SearchOption,
  112.                                   Optional ByVal dirPathPatterns As IEnumerable(Of String) = Nothing,
  113.                                   Optional ByVal dirNamePatterns As IEnumerable(Of String) = Nothing,
  114.                                   Optional ByVal ignoreCase As Boolean = True,
  115.                                   Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of DirectoryInfo)
  116.  
  117.        ' Analyze and resolve path problems. (eg. 'C:' -> 'C:\')
  118.        AnalyzePath(dirPath)
  119.  
  120.        ' Analyze the passed arguments.
  121.        AnalyzeArgs(dirPath, searchOption)
  122.  
  123.        ' Get and return the directories.
  124.        Dim queue As New ConcurrentQueue(Of DirectoryInfo)
  125.        CollectDirs(queue, dirPath, searchOption, dirPathPatterns, dirNamePatterns, ignoreCase, throwOnError)
  126.        Return queue.AsEnumerable
  127.  
  128.    End Function
  129.  
  130.    ''' <summary>
  131.    ''' Gets the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  132.    ''' </summary>
  133.    ''' <param name="dirPath">The root directory path to search for directories.</param>
  134.    ''' <param name="searchOption">The searching mode.</param>
  135.    ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  136.    ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  137.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  138.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to directory.</param>
  139.    ''' <returns>An <see cref="IEnumerable(Of String)"/> instance containing the directory paths.</returns>
  140.    ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  141.    Public Shared Function GetDirPaths(ByVal dirPath As String,
  142.                                       ByVal searchOption As SearchOption,
  143.                                       Optional ByVal dirPathPatterns As IEnumerable(Of String) = Nothing,
  144.                                       Optional ByVal dirNamePatterns As IEnumerable(Of String) = Nothing,
  145.                                       Optional ByVal ignoreCase As Boolean = True,
  146.                                       Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of String)
  147.  
  148.        ' Analyze and resolve path problems. (eg. 'C:' -> 'C:\')
  149.        AnalyzePath(dirPath)
  150.  
  151.        ' Analyze the passed arguments.
  152.        AnalyzeArgs(dirPath, searchOption)
  153.  
  154.        ' Get and return the directory paths.
  155.        Dim queue As New ConcurrentQueue(Of String)
  156.        CollectDirPaths(queue, dirPath, searchOption, dirPathPatterns, dirNamePatterns, ignoreCase, throwOnError)
  157.        Return queue.AsEnumerable
  158.  
  159.    End Function
  160.  
  161. #End Region
  162.  
  163. #Region " Private Methods "
  164.  
  165.    ''' <summary>
  166.    ''' Analyzes a directory path and perform specific changes on it.
  167.    ''' </summary>
  168.    ''' <param name="dirPath">The directory path.</param>
  169.    ''' <exception cref="System.ArgumentNullException">dirPath;Value is null, empty, or white-spaced.</exception>
  170.    Private Shared Sub AnalyzePath(ByRef dirPath As String)
  171.  
  172.        If String.IsNullOrEmpty(dirPath) OrElse String.IsNullOrWhiteSpace(dirPath) Then
  173.            Throw New ArgumentNullException("dirPath", "Value is null, empty, or white-spaced.")
  174.  
  175.        Else
  176.            ' Trim unwanted characters.
  177.            dirPath = dirPath.TrimStart({" "c}).TrimEnd({" "c})
  178.  
  179.            If Path.IsPathRooted(dirPath) Then
  180.                ' The root paths contained on the returned FileInfo objects will start with the same string-case as this root path.
  181.                ' So just for a little visual improvement, I'll treat this root path as a Drive-Letter and I convert it to UpperCase.
  182.                dirPath = Char.ToUpper(dirPath.First) & dirPath.Substring(1)
  183.            End If
  184.  
  185.            If Not dirPath.EndsWith("\"c) Then
  186.                ' Possibly its a drive letter without backslash ('C:') or else just a normal path without backslash ('C\Dir').
  187.                ' In any case, fix the ending backslash.
  188.                dirPath = dirPath.Insert(dirPath.Length, "\"c)
  189.            End If
  190.  
  191.        End If
  192.  
  193.    End Sub
  194.  
  195.    ''' <summary>
  196.    ''' Analyzes the specified directory values.
  197.    ''' </summary>
  198.    ''' <param name="dirPath">The root directory path to search for files.</param>
  199.    ''' <param name="searchOption">The searching mode.</param>
  200.    ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  201.    Private Shared Sub AnalyzeArgs(ByVal dirPath As String, ByVal searchOption As SearchOption)
  202.  
  203.        If Not Directory.Exists(dirPath) Then
  204.            Throw New ArgumentException(String.Format("Directory doesn't exists: '{0}'", dirPath), "dirPath")
  205.  
  206.        ElseIf (searchOption <> searchOption.TopDirectoryOnly) AndAlso (searchOption <> searchOption.AllDirectories) Then
  207.            Throw New ArgumentException(String.Format("Value of '{0}' is not valid enumeration value.", CStr(searchOption)), "searchOption")
  208.  
  209.        End If
  210.  
  211.    End Sub
  212.  
  213.    ''' <summary>
  214.    ''' Tries to instance the byreferred <see cref="DirectoryInfo"/> object using the given directory path.
  215.    ''' </summary>
  216.    ''' <param name="dirPath">The directory path used to instance the byreffered <see cref="DirectoryInfo"/> object.</param>
  217.    ''' <param name="dirInfo">The byreffered <see cref="DirectoryInfo"/> object to instance it using the given directory path.</param>
  218.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to directory.</param>
  219.    Private Shared Sub SetupDirInfoObject(ByVal dirPath As String,
  220.                                          ByRef dirInfo As DirectoryInfo,
  221.                                          ByVal throwOnError As Boolean)
  222.  
  223.        Try
  224.            dirInfo = New DirectoryInfo(dirPath)
  225.  
  226.        Catch ex As Exception
  227.  
  228.            Select Case ex.GetType ' Handle or suppress exceptions by its type,
  229.  
  230.                ' I've wrote different types just to feel free to expand this feature in the future.
  231.                Case GetType(ArgumentNullException),
  232.                     GetType(ArgumentException),
  233.                     GetType(Security.SecurityException),
  234.                     GetType(PathTooLongException),
  235.                     ex.GetType
  236.  
  237.                    If throwOnError Then
  238.                        Throw
  239.                    End If
  240.  
  241.            End Select
  242.  
  243.        End Try
  244.  
  245.    End Sub
  246.  
  247.    ''' <summary>
  248.    ''' Tries to instance the byreferred <paramref name="col"/> object using the given directory path.
  249.    ''' </summary>
  250.    ''' <typeparam name="A">The type of the <paramref name="col"/> object used to cast and fill the byreffered collection.</typeparam>
  251.    ''' <param name="objectAction">The method to invoke, only for <see cref="FileInfo"/> or <see cref="DirectoryInfo"/> objects, this parameter can be <c>Nothing</c>.</param>
  252.    ''' <param name="sharedAction">The method to invoke, only for filepaths or directorypaths, this parameter can be <c>Nothing</c>.</param>
  253.    ''' <param name="dirPath">The directory path used to instance the byreffered <paramref name="col"/> object.</param>
  254.    ''' <param name="searchPattern">The search pattern to list files or directories.</param>
  255.    ''' <param name="col">The byreffered <see cref="IEnumerable(Of A)"/> object to instance it using the given directory path.</param>
  256.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  257.    Private Shared Sub SetupFileDirCollection(Of A)(ByVal objectAction As Func(Of String,
  258.                                                                               SearchOption,
  259.                                                                               IEnumerable(Of A)),
  260.                                                    ByVal sharedAction As Func(Of String,
  261.                                                                             String,
  262.                                                                             SearchOption,
  263.                                                                             IEnumerable(Of A)),
  264.                                                    ByVal dirPath As String,
  265.                                                    ByVal searchPattern As String,
  266.                                                    ByRef col As IEnumerable(Of A),
  267.                                                    ByVal throwOnError As Boolean)
  268.  
  269.        Try
  270.            If objectAction IsNot Nothing Then
  271.                col = objectAction.Invoke(searchPattern, SearchOption.TopDirectoryOnly)
  272.  
  273.            ElseIf sharedAction IsNot Nothing Then
  274.                col = sharedAction.Invoke(dirPath, searchPattern, SearchOption.TopDirectoryOnly)
  275.  
  276.            Else
  277.                Throw New ArgumentException("Any Action has been defined.")
  278.  
  279.            End If
  280.  
  281.        Catch ex As Exception
  282.  
  283.            Select Case ex.GetType ' Handle or suppress exceptions by its type,
  284.  
  285.                ' I've wrote different types just to feel free to expand this feature in the future.
  286.                Case GetType(UnauthorizedAccessException),
  287.                     GetType(DirectoryNotFoundException),
  288.                     ex.GetType
  289.  
  290.                    If throwOnError Then
  291.                        Throw
  292.                    End If
  293.  
  294.            End Select
  295.  
  296.        End Try
  297.  
  298.    End Sub
  299.  
  300.    ''' <summary>
  301.    ''' Determines whether at least one of the specified patterns matches the given value.
  302.    ''' </summary>
  303.    ''' <param name="value">The value, which can be a filename, file extension, direcrory path, or directory name.</param>
  304.    ''' <param name="patterns">The patterns to match the given value.</param>
  305.    ''' <param name="ignoreCase">if set to <c>true</c>, compares ignoring string-case rules.</param>
  306.    ''' <returns><c>true</c> at least one of the specified patterns matches the given value; <c>false</c> otherwise.</returns>
  307.    Private Shared Function IsMatchPattern(ByVal value As String,
  308.                                           ByVal patterns As IEnumerable(Of String),
  309.                                           ByVal ignoreCase As Boolean) As Boolean
  310.  
  311.        ' Iterate the filename pattern(s) to match each name pattern on the current name.
  312.        For Each pattern As String In patterns
  313.  
  314.            ' Supress consecuent conditionals if pattern its an asterisk.
  315.            If pattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  316.                Return True
  317.  
  318.            ElseIf ignoreCase Then ' Compare name ignoring string-case rules.
  319.                If value.ToLower Like pattern.ToLower Then
  320.                    Return True
  321.                End If
  322.  
  323.            Else ' Compare filename unignoring string-case rules.
  324.                If value Like pattern Then
  325.                    Return True
  326.                End If
  327.  
  328.            End If ' ignoreCase
  329.  
  330.        Next pattern
  331.  
  332.        Return False
  333.  
  334.    End Function
  335.  
  336.    ''' <summary>
  337.    ''' Runs the next collector tasks synchronouslly.
  338.    ''' </summary>
  339.    ''' <typeparam name="T"></typeparam>
  340.    ''' <param name="action">The collector method to invoke.</param>
  341.    ''' <param name="queue">The <see cref="ConcurrentQueue(Of FileInfo)"/> instance.</param>
  342.    ''' <param name="dirPath">The directory path.</param>
  343.    ''' <param name="firstPatterns">The first comparison patterns.</param>
  344.    ''' <param name="secondPatterns">The second comparison patterns.</param>
  345.    ''' <param name="ignoreCase">if set to <c>true</c>, compares ignoring string-case rules.</param>
  346.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  347.    Private Shared Sub RunNextTasks(Of T)(ByVal action As Action(Of ConcurrentQueue(Of T),
  348.                                                                 String,
  349.                                                                 SearchOption,
  350.                                                                 IEnumerable(Of String),
  351.                                                                 IEnumerable(Of String),
  352.                                                                 Boolean,
  353.                                                                 Boolean),
  354.                                          ByVal queue As ConcurrentQueue(Of T),
  355.                                          ByVal dirPath As String,
  356.                                          ByVal firstPatterns As IEnumerable(Of String),
  357.                                          ByVal secondPatterns As IEnumerable(Of String),
  358.                                          ByVal ignoreCase As Boolean,
  359.                                          ByVal throwOnError As Boolean)
  360.  
  361.        Try
  362.            Task.WaitAll(New DirectoryInfo(dirPath).
  363.                             GetDirectories.
  364.                             Select(Function(dir As DirectoryInfo)
  365.                                        Return Task.Factory.StartNew(Sub()
  366.                                                                         action.Invoke(queue,
  367.                                                                                       dir.FullName, SearchOption.AllDirectories,
  368.                                                                                       firstPatterns, secondPatterns,
  369.                                                                                       ignoreCase, throwOnError)
  370.                                                                     End Sub)
  371.                                    End Function).ToArray)
  372.  
  373.        Catch ex As Exception
  374.  
  375.            Select Case ex.GetType ' Handle or suppress exceptions by its type,
  376.  
  377.                ' I've wrote different types just to feel free to expand this feature in the future.
  378.                Case GetType(UnauthorizedAccessException),
  379.                     GetType(DirectoryNotFoundException),
  380.                     ex.GetType
  381.  
  382.                    If throwOnError Then
  383.                        Throw
  384.                    End If
  385.  
  386.            End Select
  387.  
  388.        End Try
  389.  
  390.    End Sub
  391.  
  392.    ''' <summary>
  393.    ''' Collects the files those matches the criteria inside the specified directory and/or sub-directories.
  394.    ''' </summary>
  395.    ''' <param name="queue">The <see cref="ConcurrentQueue(Of FileInfo)"/> instance to enqueue new files.</param>
  396.    ''' <param name="dirPath">The root directory path to search for files.</param>
  397.    ''' <param name="searchOption">The searching mode.</param>
  398.    ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  399.    ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  400.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  401.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  402.    Private Shared Sub CollectFiles(ByVal queue As ConcurrentQueue(Of FileInfo),
  403.                                    ByVal dirPath As String,
  404.                                    ByVal searchOption As SearchOption,
  405.                                    ByVal fileNamePatterns As IEnumerable(Of String),
  406.                                    ByVal fileExtPatterns As IEnumerable(Of String),
  407.                                    ByVal ignoreCase As Boolean,
  408.                                    ByVal throwOnError As Boolean)
  409.  
  410.        ' Initialize a FileInfo collection.
  411.        Dim fileInfoCol As IEnumerable(Of FileInfo) = Nothing
  412.  
  413.        ' Initialize a DirectoryInfo.
  414.        Dim dirInfo As DirectoryInfo = Nothing
  415.        SetupDirInfoObject(dirPath, dirInfo, throwOnError)
  416.  
  417.        If fileExtPatterns IsNot Nothing Then
  418.            ' Decrease time execution by searching for files that has extension.
  419.            SetupFileDirCollection(Of FileInfo)(AddressOf dirInfo.GetFiles, Nothing,
  420.                                                dirInfo.FullName, "*.*", fileInfoCol, throwOnError)
  421.        Else
  422.            ' Search for all files.
  423.            SetupFileDirCollection(Of FileInfo)(AddressOf dirInfo.GetFiles, Nothing,
  424.                                                dirInfo.FullName, "*", fileInfoCol, throwOnError)
  425.        End If
  426.  
  427.        ' If the fileInfoCol collection is not empty then...
  428.        If fileInfoCol IsNot Nothing Then
  429.  
  430.            ' Iterate the files.
  431.            For Each fInfo As FileInfo In fileInfoCol
  432.  
  433.                ' Flag to determine whether a filename pattern is matched. Activated by default.
  434.                Dim flagNamePattern As Boolean = True
  435.  
  436.                ' Flag to determine whether a file extension pattern is matched. Activated by default.
  437.                Dim flagExtPattern As Boolean = True
  438.  
  439.                ' If filename patterns collection is not empty then...
  440.                If fileNamePatterns IsNot Nothing Then
  441.                    flagNamePattern = IsMatchPattern(fInfo.Name, fileNamePatterns, ignoreCase)
  442.                End If
  443.  
  444.                ' If file extension patterns collection is not empty then...
  445.                If fileExtPatterns IsNot Nothing Then
  446.                    flagExtPattern = IsMatchPattern(fInfo.Extension, fileExtPatterns, ignoreCase)
  447.                End If
  448.  
  449.                ' If fileName and also fileExtension patterns are matched then...
  450.                If flagNamePattern AndAlso flagExtPattern Then
  451.                    queue.Enqueue(fInfo) ' Enqueue this FileInfo object.
  452.                End If
  453.  
  454.            Next fInfo
  455.  
  456.        End If ' fileInfoCol IsNot Nothing
  457.  
  458.        ' If searchOption is recursive then...
  459.        If searchOption = searchOption.AllDirectories Then
  460.            RunNextTasks(Of FileInfo)(AddressOf CollectFiles,
  461.                                      queue, dirInfo.FullName, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  462.        End If
  463.  
  464.    End Sub
  465.  
  466.    ''' <summary>
  467.    ''' Collects the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  468.    ''' </summary>
  469.    ''' <param name="queue">The <see cref="ConcurrentQueue(Of String)"/> instance to enqueue new filepaths.</param>
  470.    ''' <param name="dirPath">The root directory path to search for files.</param>
  471.    ''' <param name="searchOption">The searching mode.</param>
  472.    ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  473.    ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  474.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  475.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  476.    Private Shared Sub CollectFilePaths(ByVal queue As ConcurrentQueue(Of String),
  477.                                        ByVal dirPath As String,
  478.                                        ByVal searchOption As SearchOption,
  479.                                        ByVal fileNamePatterns As IEnumerable(Of String),
  480.                                        ByVal fileExtPatterns As IEnumerable(Of String),
  481.                                        ByVal ignoreCase As Boolean,
  482.                                        ByVal throwOnError As Boolean)
  483.  
  484.        ' Initialize a filepath collection.
  485.        Dim filePathCol As IEnumerable(Of String) = Nothing
  486.  
  487.        If fileExtPatterns IsNot Nothing Then
  488.            ' Decrease time execution by searching for files that has extension.
  489.            SetupFileDirCollection(Of String)(Nothing, AddressOf Directory.GetFiles,
  490.                                              dirPath, "*.*", filePathCol, throwOnError)
  491.        Else
  492.            ' Search for all files.
  493.            SetupFileDirCollection(Of String)(Nothing, AddressOf Directory.GetFiles,
  494.                                              dirPath, "*", filePathCol, throwOnError)
  495.        End If
  496.  
  497.        ' If the filepath collection is not empty then...
  498.        If filePathCol IsNot Nothing Then
  499.  
  500.            ' Iterate the filepaths.
  501.            For Each filePath As String In filePathCol
  502.  
  503.                ' Flag to determine whether a filename pattern is matched. Activated by default.
  504.                Dim flagNamePattern As Boolean = True
  505.  
  506.                ' Flag to determine whether a file extension pattern is matched. Activated by default.
  507.                Dim flagExtPattern As Boolean = True
  508.  
  509.                ' If filename patterns collection is not empty then...
  510.                If fileNamePatterns IsNot Nothing Then
  511.                    flagNamePattern = IsMatchPattern(Path.GetFileNameWithoutExtension(filePath), fileNamePatterns, ignoreCase)
  512.                End If
  513.  
  514.                ' If file extension patterns collection is not empty then...
  515.                If fileExtPatterns IsNot Nothing Then
  516.                    flagExtPattern = IsMatchPattern(Path.GetExtension(filePath), fileExtPatterns, ignoreCase)
  517.                End If
  518.  
  519.                ' If fileName and also fileExtension patterns are matched then...
  520.                If flagNamePattern AndAlso flagExtPattern Then
  521.                    queue.Enqueue(filePath) ' Enqueue this filepath.
  522.                End If
  523.  
  524.            Next filePath
  525.  
  526.        End If ' filePathCol IsNot Nothing
  527.  
  528.        ' If searchOption is recursive then...
  529.        If searchOption = searchOption.AllDirectories Then
  530.            RunNextTasks(Of String)(AddressOf CollectFilePaths,
  531.                                    queue, dirPath, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  532.        End If
  533.  
  534.    End Sub
  535.  
  536.    ''' <summary>
  537.    ''' Collects the directories those matches the criteria inside the specified directory and/or sub-directories.
  538.    ''' </summary>
  539.    ''' <param name="queue">The <see cref="ConcurrentQueue(Of DirectoryInfo)"/> instance to enqueue new directories.</param>
  540.    ''' <param name="dirPath">The root directory path to search for directories.</param>
  541.    ''' <param name="searchOption">The searching mode.</param>
  542.    ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  543.    ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  544.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  545.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to directory.</param>
  546.    Private Shared Sub CollectDirs(ByVal queue As ConcurrentQueue(Of DirectoryInfo),
  547.                                   ByVal dirPath As String,
  548.                                   ByVal searchOption As SearchOption,
  549.                                   ByVal dirPathPatterns As IEnumerable(Of String),
  550.                                   ByVal dirNamePatterns As IEnumerable(Of String),
  551.                                   ByVal ignoreCase As Boolean,
  552.                                   ByVal throwOnError As Boolean)
  553.  
  554.        ' Initialize a DirectoryInfo collection.
  555.        Dim dirInfoCol As IEnumerable(Of DirectoryInfo) = Nothing
  556.  
  557.        ' Initialize a DirectoryInfo.
  558.        Dim dirInfo As DirectoryInfo = Nothing
  559.        SetupDirInfoObject(dirPath, dirInfo, throwOnError)
  560.  
  561.        ' Get the top directories of the current directory.
  562.        SetupFileDirCollection(Of DirectoryInfo)(AddressOf dirInfo.GetDirectories, Nothing,
  563.                                                 dirInfo.FullName, "*", dirInfoCol, throwOnError)
  564.  
  565.        ' If the fileInfoCol collection is not empty then...
  566.        If dirInfoCol IsNot Nothing Then
  567.  
  568.            ' Iterate the files.
  569.            For Each dir As DirectoryInfo In dirInfoCol
  570.  
  571.                ' Flag to determine whether a directory path pattern is matched. Activated by default.
  572.                Dim flagPathPattern As Boolean = True
  573.  
  574.                ' Flag to determine whether a directory name pattern is matched. Activated by default.
  575.                Dim flagNamePattern As Boolean = True
  576.  
  577.                ' If directory path patterns collection is not empty then...
  578.                If dirPathPatterns IsNot Nothing Then
  579.                    flagPathPattern = IsMatchPattern(dir.FullName, dirPathPatterns, ignoreCase)
  580.                End If
  581.  
  582.                ' If directory name patterns collection is not empty then...
  583.                If dirNamePatterns IsNot Nothing Then
  584.                    flagNamePattern = IsMatchPattern(dir.Name, dirNamePatterns, ignoreCase)
  585.                End If
  586.  
  587.                ' If directory path and also directory name patterns are matched then...
  588.                If flagPathPattern AndAlso flagNamePattern Then
  589.                    queue.Enqueue(dir) ' Enqueue this DirectoryInfo object.
  590.                End If
  591.  
  592.            Next dir
  593.  
  594.        End If ' dirInfoCol IsNot Nothing
  595.  
  596.        ' If searchOption is recursive then...
  597.        If searchOption = searchOption.AllDirectories Then
  598.            RunNextTasks(Of DirectoryInfo)(AddressOf CollectDirs,
  599.                                           queue, dirPath, dirPathPatterns, dirNamePatterns, ignoreCase, throwOnError)
  600.        End If
  601.  
  602.    End Sub
  603.  
  604.    ''' <summary>
  605.    ''' Collects the directory paths those matches the criteria inside the specified directory and/or sub-directories.
  606.    ''' </summary>
  607.    ''' <param name="queue">The <see cref="ConcurrentQueue(Of String)"/> instance to enqueue new directory paths.</param>
  608.    ''' <param name="dirPath">The root directory path to search for directories.</param>
  609.    ''' <param name="searchOption">The searching mode.</param>
  610.    ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  611.    ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  612.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  613.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to directory.</param>
  614.    Private Shared Sub CollectDirPaths(ByVal queue As ConcurrentQueue(Of String),
  615.                                       ByVal dirPath As String,
  616.                                       ByVal searchOption As SearchOption,
  617.                                       ByVal dirPathPatterns As IEnumerable(Of String),
  618.                                       ByVal dirNamePatterns As IEnumerable(Of String),
  619.                                       ByVal ignoreCase As Boolean,
  620.                                       ByVal throwOnError As Boolean)
  621.  
  622.        ' Initialize a directory paths collection.
  623.        Dim dirPathCol As IEnumerable(Of String) = Nothing
  624.  
  625.        ' Get the top directory paths of the current directory.
  626.        SetupFileDirCollection(Of String)(Nothing, AddressOf Directory.GetDirectories,
  627.                                          dirPath, "*", dirPathCol, throwOnError)
  628.  
  629.        ' If the fileInfoCol collection is not empty then...
  630.        If dirPathCol IsNot Nothing Then
  631.  
  632.            ' Iterate the files.
  633.            For Each dir As String In dirPathCol
  634.  
  635.                ' Flag to determine whether a directory path pattern is matched. Activated by default.
  636.                Dim flagPathPattern As Boolean = True
  637.  
  638.                ' Flag to determine whether a directory name pattern is matched. Activated by default.
  639.                Dim flagNamePattern As Boolean = True
  640.  
  641.                ' If directory path patterns collection is not empty then...
  642.                If dirPathPatterns IsNot Nothing Then
  643.                    flagPathPattern = IsMatchPattern(dir, dirPathPatterns, ignoreCase)
  644.                End If
  645.  
  646.                ' If directory name patterns collection is not empty then...
  647.                If dirNamePatterns IsNot Nothing Then
  648.                    flagNamePattern = IsMatchPattern(Path.GetFileName(dir), dirNamePatterns, ignoreCase)
  649.                End If
  650.  
  651.                ' If directory path and also directory name patterns are matched then...
  652.                If flagPathPattern AndAlso flagNamePattern Then
  653.                    queue.Enqueue(dir) ' Enqueue this directory path.
  654.                End If
  655.  
  656.            Next dir
  657.  
  658.        End If ' dirPathCol IsNot Nothing
  659.  
  660.        ' If searchOption is recursive then...
  661.        If searchOption = searchOption.AllDirectories Then
  662.            RunNextTasks(Of String)(AddressOf CollectDirPaths,
  663.                                    queue, dirPath, dirPathPatterns, dirNamePatterns, ignoreCase, throwOnError)
  664.        End If
  665.  
  666.    End Sub
  667.  
  668. #End Region
  669.  
  670. End Class
  671.  
  672. #End Region
« Última modificación: 14 Febrero 2015, 21:40 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #453 en: 16 Febrero 2015, 13:48 pm »

Una manera sencilla de medír el tiempo de ejecución de un método, útil para llevar a cabo análisis/comparaciones.

( Los resultados se puedne mostrar en un messageBox o en la consola de depuración, usando el parámetro opcional. )

Modo de empleo:
Código
  1.    MeasureAction(Sub()
  2.                      For x As Integer = 0 To 5000
  3.                          Debug.WriteLine(x)
  4.                      Next
  5.                  End Sub)

O bien:
Código
  1.    MeasureAction(AddressOf Test)
  2.  
  3.    Private Function Test() As Boolean
  4.        ' Esto provocará un error:
  5.        Return CTypeDynamic(Of Boolean)("")
  6.    End Function

Source:
Código
  1.    ''' <remarks>
  2.    ''' *****************************************************************
  3.    ''' Snippet Title: Measure Code Execution Time
  4.    ''' Code's Author: Elektro
  5.    ''' Date Modified: 16-February-2015
  6.    ''' Usage Example:
  7.    ''' MeasureAction(AddressOf MyMethodName, writeResultInConsole:=True)
  8.    '''
  9.    ''' MeasureAction(Sub()
  10.    '''                   ' My Method Lambda...
  11.    '''               End Sub)
  12.    ''' *****************************************************************
  13.    ''' </remarks>
  14.    ''' <summary>
  15.    ''' Measures the code execution time of a method.
  16.    ''' </summary>
  17.    ''' <param name="action">The action to be invoked.</param>
  18.    ''' <param name="writeResultInConsole">
  19.    ''' If set to <c>true</c>, print the results in console instead of displaying a <see cref="MessageBox"/>.
  20.    ''' </param>
  21.    Private Sub MeasureAction(ByVal action As Action,
  22.                              Optional ByVal writeResultInConsole As Boolean = False)
  23.  
  24.        ' Measures the elapsed time.
  25.        Dim timeWatch As New Stopwatch
  26.  
  27.        ' The time display format (Hours:Minutes:Secons:Milliseconds)
  28.        Dim timeFormat As String = "hh\:mm\:ss\:fff"
  29.  
  30.        ' Flag that determines whether the method invocation has succeed.
  31.        Dim success As Boolean = False
  32.  
  33.        ' Captures any exception caused by the invoked method.
  34.        Dim invokeEx As Exception = Nothing
  35.  
  36.        ' Retains and formats the information string.
  37.        Dim sb As New System.Text.StringBuilder
  38.  
  39.        ' Determines the MessageBox icon.
  40.        Dim msgIcon As MessageBoxIcon
  41.  
  42.        ' Determines the MessageBox buttons.
  43.        Dim msgButtons As MessageBoxButtons
  44.  
  45.        ' Determines the MessageBox result.
  46.        Dim msgResult As DialogResult
  47.  
  48.        ' Start to measure time.
  49.        timeWatch.Start()
  50.  
  51.        Try
  52.            ' Invoke the method.
  53.            action.Invoke()
  54.            success = True
  55.  
  56.        Catch ex As Exception
  57.            ' Capture the exception details.
  58.            invokeEx = ex
  59.            success = False
  60.  
  61.        Finally
  62.            ' Ensure to stop measuring time.
  63.            timeWatch.Stop()
  64.  
  65.        End Try
  66.  
  67.        Select Case success
  68.  
  69.            Case True
  70.                With sb ' Set an information message.
  71.                    .AppendLine(String.Format("Method Name: {0}", action.Method.Name))
  72.                    .AppendLine()
  73.                    .AppendLine(String.Format("Elapsed Time: {0}", timeWatch.Elapsed.ToString(timeFormat)))
  74.                End With
  75.  
  76.            Case Else
  77.                With sb ' Set an error message.
  78.                    .AppendLine("Exception occurred during code execution measuring.")
  79.                    .AppendLine()
  80.                    .AppendLine(String.Format("Method Name: {0}", action.Method.Name))
  81.                    .AppendLine()
  82.                    .AppendLine(String.Format("Exception Type: {0}", invokeEx.GetType.Name))
  83.                    .AppendLine()
  84.                    .AppendLine("Exception Message:")
  85.                    .AppendLine(invokeEx.Message)
  86.                    .AppendLine()
  87.                    .AppendLine("Exception Stack Trace:")
  88.                    .AppendLine(invokeEx.StackTrace)
  89.                End With
  90.  
  91.        End Select
  92.  
  93.        If writeResultInConsole Then ' Print results in console.
  94.            Debug.WriteLine(String.Join(Environment.NewLine,
  95.                                        sb.ToString.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)))
  96.  
  97.        Else
  98.            ' Show the MessageBox with the information string.
  99.            msgIcon = If(success, MessageBoxIcon.Information, MessageBoxIcon.Error)
  100.            msgButtons = If(success, MessageBoxButtons.OK, MessageBoxButtons.RetryCancel)
  101.            msgResult = MessageBox.Show(sb.ToString, "Code Execution Measurer", msgButtons, msgIcon)
  102.  
  103.            ' If invoked method has failed, retry or cancel.
  104.            If Not success AndAlso (msgResult = DialogResult.Retry) Then
  105.                MeasureAction(action, writeResultInConsole)
  106.            End If
  107.  
  108.        End If
  109.  
  110.    End Sub
« Última modificación: 16 Febrero 2015, 13:50 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #454 en: 15 Marzo 2015, 02:23 am »

He desarrollado este snippet para administrar las capacidades de arrastrar (dragging) en tiempo de ejecución, de uno o varios Forms, extendiendo el control y la eficiencia de los típicos códigos "copy&paste" que se pueden encontrar por internet para llevar a cabo dicha tarea.

Ejemplos de uso:
Código
  1. Public Class Form1
  2.  
  3.    ''' <summary>
  4.    ''' The <see cref="FormDragger"/> instance that manages the form(s) dragging.
  5.    ''' </summary>
  6.    Private formDragger As FormDragger = FormDragger.Empty
  7.  
  8.    Private Sub Test() Handles MyBase.Shown
  9.        Me.InitializeDrag()
  10.    End Sub
  11.  
  12.    Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
  13.    Handles Button1.Click
  14.  
  15.        Me.AlternateDragEnabled(Me)
  16.  
  17.    End Sub
  18.  
  19.    Private Sub InitializeDrag()
  20.  
  21.        ' 1st way, using the single-Form constructor:
  22.        Me.formDragger = New FormDragger(Me, enabled:=True, cursor:=Cursors.SizeAll)
  23.  
  24.        ' 2nd way, using the multiple-Forms constructor:
  25.        ' Me.formDragger = New FormDragger({Me, Form2, form3})
  26.  
  27.        ' 3rd way, using the default constructor then adding a Form into the collection:
  28.        ' Me.formDragger = New FormDragger
  29.        ' Me.formDragger.AddForm(Me, enabled:=True, cursor:=Cursors.SizeAll)
  30.  
  31.    End Sub
  32.  
  33.    ''' <summary>
  34.    ''' Alternates the dragging of the specified form.
  35.    ''' </summary>
  36.    ''' <param name="form">The form.</param>
  37.    Private Sub AlternateDragEnabled(ByVal form As Form)
  38.  
  39.        Dim formInfo As FormDragger.FormDragInfo = Me.formDragger.FindFormDragInfo(form)
  40.        formInfo.Enabled = Not formInfo.Enabled
  41.  
  42.    End Sub
  43.  
  44. End Class

Source:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 15-March-2015
  4. ' ***********************************************************************
  5. ' <copyright file="FormDragger.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Option Statements "
  11.  
  12. Option Explicit On
  13. Option Strict On
  14. Option Infer Off
  15.  
  16. #End Region
  17.  
  18. #Region " Usage Examples "
  19.  
  20. 'Public Class Form1
  21.  
  22. '    ''' <summary>
  23. '    ''' The <see cref="FormDragger"/> instance that manages the form(s) dragging.
  24. '    ''' </summary>
  25. '    Private formDragger As FormDragger = FormDragger.Empty
  26.  
  27. '    Private Sub Test() Handles MyBase.Shown
  28. '        Me.InitializeDrag()
  29. '    End Sub
  30.  
  31. '    Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
  32. '    Handles Button1.Click
  33.  
  34. '        Me.AlternateDragEnabled(Me)
  35.  
  36. '    End Sub
  37.  
  38. '    Private Sub InitializeDrag()
  39.  
  40. '        ' 1st way, using the single-Form constructor:
  41. '        Me.formDragger = New FormDragger(Me, enabled:=True, cursor:=Cursors.SizeAll)
  42.  
  43. '        ' 2nd way, using the multiple-Forms constructor:
  44. '        ' Me.formDragger = New FormDragger({Me, Form2, form3})
  45.  
  46. '        ' 3rd way, using the default constructor then adding a Form into the collection:
  47. '        ' Me.formDragger = New FormDragger
  48. '        ' Me.formDragger.AddForm(Me, enabled:=True, cursor:=Cursors.SizeAll)
  49.  
  50. '    End Sub
  51.  
  52. '    ''' <summary>
  53. '    ''' Alternates the dragging of the specified form.
  54. '    ''' </summary>
  55. '    ''' <param name="form">The form.</param>
  56. '    Private Sub AlternateDragEnabled(ByVal form As Form)
  57.  
  58. '        Dim formInfo As FormDragger.FormDragInfo = Me.formDragger.FindFormDragInfo(form)
  59. '        formInfo.Enabled = Not formInfo.Enabled
  60.  
  61. '    End Sub
  62.  
  63. 'End Class
  64.  
  65. #End Region
  66.  
  67. #Region " Imports "
  68.  
  69. Imports System.ComponentModel
  70.  
  71. #End Region
  72.  
  73. #Region " Form Dragger "
  74.  
  75. ''' <summary>
  76. ''' Enable or disable drag at runtime on a <see cref="Form"/>.
  77. ''' </summary>
  78. Public NotInheritable Class FormDragger : Implements IDisposable
  79.  
  80. #Region " Properties "
  81.  
  82.    ''' <summary>
  83.    ''' Gets an <see cref="IEnumerable(Of Form)"/> collection that contains the Forms capables to perform draggable operations.
  84.    ''' </summary>
  85.    ''' <value>The <see cref="IEnumerable(Of Form)"/>.</value>
  86.    <EditorBrowsable(EditorBrowsableState.Always)>
  87.    Public ReadOnly Property Forms As IEnumerable(Of FormDragInfo)
  88.        Get
  89.            Return Me.forms1
  90.        End Get
  91.    End Property
  92.    ''' <summary>
  93.    ''' An <see cref="IEnumerable(Of Form)"/> collection that contains the Forms capables to perform draggable operations.
  94.    ''' </summary>
  95.    Private forms1 As IEnumerable(Of FormDragInfo) = {}
  96.  
  97.    ''' <summary>
  98.    ''' Represents a <see cref="FormDragger"/> instance that is <c>Nothing</c>.
  99.    ''' </summary>
  100.    ''' <value><c>Nothing</c></value>
  101.    <EditorBrowsable(EditorBrowsableState.Always)>
  102.    Public Shared ReadOnly Property Empty As FormDragger
  103.        Get
  104.            Return Nothing
  105.        End Get
  106.    End Property
  107.  
  108. #End Region
  109.  
  110. #Region " Types "
  111.  
  112.    ''' <summary>
  113.    ''' Defines the draggable info of a <see cref="Form"/>.
  114.    ''' </summary>
  115.    <Serializable>
  116.    Public NotInheritable Class FormDragInfo
  117.  
  118. #Region " Properties "
  119.  
  120.        ''' <summary>
  121.        ''' Gets the associated <see cref="Form"/> used to perform draggable operations.
  122.        ''' </summary>
  123.        ''' <value>The associated <see cref="Form"/>.</value>
  124.        <EditorBrowsable(EditorBrowsableState.Always)>
  125.        Public ReadOnly Property Form As Form
  126.            Get
  127.                Return form1
  128.            End Get
  129.        End Property
  130.        ''' <summary>
  131.        ''' The associated <see cref="Form"/>
  132.        ''' </summary>
  133.        <NonSerialized>
  134.        Private ReadOnly form1 As Form
  135.  
  136.        ''' <summary>
  137.        ''' Gets the name of the associated <see cref="Form"/>.
  138.        ''' </summary>
  139.        ''' <value>The Form.</value>
  140.        <EditorBrowsable(EditorBrowsableState.Always)>
  141.        Public ReadOnly Property Name As String
  142.            Get
  143.                If Me.Form IsNot Nothing Then
  144.                    Return Form.Name
  145.                Else
  146.                    Return String.Empty
  147.                End If
  148.            End Get
  149.        End Property
  150.  
  151.        ''' <summary>
  152.        ''' Gets or sets a value indicating whether drag is enabled on the associated <see cref="Form"/>.
  153.        ''' </summary>
  154.        ''' <value><c>true</c> if drag is enabled; otherwise, <c>false</c>.</value>
  155.        <EditorBrowsable(EditorBrowsableState.Always)>
  156.        Public Property Enabled As Boolean
  157.  
  158.        ''' <summary>
  159.        ''' A <see cref="FormDragger"/> instance instance containing the draggable information of the associated <see cref="Form"/>.
  160.        ''' </summary>
  161.        ''' <value>The draggable information.</value>
  162.        <EditorBrowsable(EditorBrowsableState.Never)>
  163.        Public Property DragInfo As FormDragger = FormDragger.Empty
  164.  
  165.        ''' <summary>
  166.        ''' Gets or sets the <see cref="Cursor"/> used to drag the associated <see cref="Form"/>.
  167.        ''' </summary>
  168.        ''' <value>The <see cref="Cursor"/>.</value>
  169.        <EditorBrowsable(EditorBrowsableState.Always)>
  170.        Public Property Cursor As Cursor = Cursors.SizeAll
  171.  
  172.        ''' <summary>
  173.        ''' Gets or sets the old form's cursor to restore it after dragging.
  174.        ''' </summary>
  175.        ''' <value>The old form's cursor.</value>
  176.        <EditorBrowsable(EditorBrowsableState.Never)>
  177.        Public Property OldCursor As Cursor = Nothing
  178.  
  179.        ''' <summary>
  180.        ''' Gets or sets the initial mouse coordinates, normally <see cref="Form.MousePosition"/>.
  181.        ''' </summary>
  182.        ''' <value>The initial mouse coordinates.</value>
  183.        <EditorBrowsable(EditorBrowsableState.Never)>
  184.        Public Property InitialMouseCoords As Point = Point.Empty
  185.  
  186.        ''' <summary>
  187.        ''' Gets or sets the initial <see cref="Form"/> location, normally <see cref="Form.Location"/>.
  188.        ''' </summary>
  189.        ''' <value>The initial location.</value>
  190.        <EditorBrowsable(EditorBrowsableState.Never)>
  191.        Public Property InitialLocation As Point = Point.Empty
  192.  
  193. #End Region
  194.  
  195. #Region " Constructors "
  196.  
  197.        ''' <summary>
  198.        ''' Initializes a new instance of the <see cref="FormDragInfo"/> class.
  199.        ''' </summary>
  200.        ''' <param name="form">The form.</param>
  201.        Public Sub New(ByVal form As Form)
  202.            Me.form1 = form
  203.            Me.Cursor = form.Cursor
  204.        End Sub
  205.  
  206.        ''' <summary>
  207.        ''' Prevents a default instance of the <see cref="FormDragInfo"/> class from being created.
  208.        ''' </summary>
  209.        Private Sub New()
  210.        End Sub
  211.  
  212. #End Region
  213.  
  214. #Region " Hidden Methods "
  215.  
  216.        ''' <summary>
  217.        ''' Serves as a hash function for a particular type.
  218.        ''' </summary>
  219.        <EditorBrowsable(EditorBrowsableState.Never)>
  220.        Public Shadows Function GetHashCode() As Integer
  221.            Return MyBase.GetHashCode
  222.        End Function
  223.  
  224.        ''' <summary>
  225.        ''' Gets the System.Type of the current instance.
  226.        ''' </summary>
  227.        ''' <returns>The exact runtime type of the current instance.</returns>
  228.        <EditorBrowsable(EditorBrowsableState.Never)>
  229.        Public Shadows Function [GetType]() As Type
  230.            Return MyBase.GetType
  231.        End Function
  232.  
  233.        ''' <summary>
  234.        ''' Determines whether the specified System.Object instances are considered equal.
  235.        ''' </summary>
  236.        <EditorBrowsable(EditorBrowsableState.Never)>
  237.        Public Shadows Function Equals(ByVal obj As Object) As Boolean
  238.            Return MyBase.Equals(obj)
  239.        End Function
  240.  
  241.        ''' <summary>
  242.        ''' Determines whether the specified System.Object instances are the same instance.
  243.        ''' </summary>
  244.        <EditorBrowsable(EditorBrowsableState.Never)>
  245.        Private Shadows Sub ReferenceEquals()
  246.        End Sub
  247.  
  248.        ''' <summary>
  249.        ''' Returns a String that represents the current object.
  250.        ''' </summary>
  251.        <EditorBrowsable(EditorBrowsableState.Never)>
  252.        Public Shadows Function ToString() As String
  253.            Return MyBase.ToString
  254.        End Function
  255.  
  256. #End Region
  257.  
  258.    End Class
  259.  
  260. #End Region
  261.  
  262. #Region " Constructors "
  263.  
  264.    ''' <summary>
  265.    ''' Initializes a new instance of the <see cref="FormDragger"/> class.
  266.    ''' </summary>
  267.    Public Sub New()
  268.        Me.forms1={}
  269.    End Sub
  270.  
  271.    ''' <summary>
  272.    ''' Initializes a new instance of the <see cref="FormDragger"/> class.
  273.    ''' </summary>
  274.    ''' <param name="form">The <see cref="Form"/> used to perform draggable operations.</param>
  275.    ''' <param name="enabled">If set to <c>true</c>, enable dragging on the <see cref="Form"/>.</param>
  276.    ''' <param name="cursor">The <see cref="Cursor"/> used to drag the specified <see cref="Form"/>.</param>
  277.    Public Sub New(ByVal form As Form,
  278.                   Optional enabled As Boolean = False,
  279.                   Optional cursor As Cursor = Nothing)
  280.  
  281.        Me.forms1 =
  282.            {
  283.                New FormDragInfo(form) With
  284.                         {
  285.                             .Enabled = enabled,
  286.                             .Cursor = cursor
  287.                         }
  288.            }
  289.  
  290.        Me.AssocHandlers(form)
  291.  
  292.    End Sub
  293.  
  294.    ''' <summary>
  295.    ''' Initializes a new instance of the <see cref="FormDragger"/> class.
  296.    ''' </summary>
  297.    ''' <param name="forms">The <see cref="Forms"/> used to perform draggable operations.</param>
  298.    Public Sub New(ByVal forms As IEnumerable(Of Form))
  299.  
  300.        Me.forms1 = (From form As Form In forms
  301.                     Select New FormDragInfo(form)).ToArray
  302.  
  303.        For Each form As Form In forms
  304.            Me.AssocHandlers(form)
  305.        Next form
  306.  
  307.    End Sub
  308.  
  309.    ''' <summary>
  310.    ''' Initializes a new instance of the <see cref="FormDragger"/> class.
  311.    ''' </summary>
  312.    ''' <param name="formInfo">
  313.    ''' The <see cref="FormDragInfo"/> instance
  314.    ''' that contains the <see cref="Form"/> reference and its draggable info.
  315.    ''' </param>
  316.    ''' <param name="mouseCoordinates">The current mouse coordinates.</param>
  317.    ''' <param name="location">The current location.</param>
  318.    Private Sub New(ByVal formInfo As FormDragInfo,
  319.                    ByVal mouseCoordinates As Point,
  320.                    ByVal location As Point)
  321.  
  322.        formInfo.InitialMouseCoords = mouseCoordinates
  323.        formInfo.InitialLocation = location
  324.  
  325.    End Sub
  326.  
  327. #End Region
  328.  
  329. #Region " Public Methods "
  330.  
  331.    ''' <summary>
  332.    ''' Adds the specified <see cref="Form"/> into the draggable <see cref="Forms"/> collection.
  333.    ''' </summary>
  334.    ''' <param name="form">The <see cref="Form"/>.</param>
  335.    ''' <param name="enabled">If set to <c>true</c>, enable dragging on the <see cref="Form"/>.</param>
  336.    ''' <param name="cursor">The <see cref="Cursor"/> used to drag the specified <see cref="Form"/>.</param>
  337.    ''' <exception cref="System.ArgumentException">The specified form is already added.;form</exception>
  338.    Public Function AddForm(ByVal form As Form,
  339.                            Optional enabled As Boolean = False,
  340.                            Optional cursor As Cursor = Nothing) As FormDragInfo
  341.  
  342.        For Each formInfo As FormDragInfo In Me.forms1
  343.  
  344.            If formInfo.Form.Equals(form) Then
  345.                Throw New ArgumentException("The specified form is already added.", "form")
  346.                Exit Function
  347.            End If
  348.  
  349.        Next formInfo
  350.  
  351.        Dim newFormInfo As New FormDragInfo(form) With {.Enabled = enabled, .Cursor = cursor}
  352.        Me.forms1 = Me.forms1.Concat({newFormInfo})
  353.        Me.AssocHandlers(form)
  354.  
  355.        Return newFormInfo
  356.  
  357.    End Function
  358.  
  359.    ''' <summary>
  360.    ''' Removes the specified <see cref="Form"/> from the draggable <see cref="Forms"/> collection.
  361.    ''' </summary>
  362.    ''' <param name="form">The form.</param>
  363.    ''' <exception cref="System.ArgumentException">The specified form is not found.;form</exception>
  364.    Public Sub RemoveForm(ByVal form As Form)
  365.  
  366.        Dim formInfoToRemove As FormDragInfo = Nothing
  367.  
  368.        For Each formInfo As FormDragInfo In Me.forms1
  369.  
  370.            If formInfo.Form.Equals(form) Then
  371.                formInfoToRemove = formInfo
  372.                Exit For
  373.            End If
  374.  
  375.        Next formInfo
  376.  
  377.        If formInfoToRemove IsNot Nothing Then
  378.  
  379.            Me.forms1 = From formInfo As FormDragInfo In Me.forms1
  380.                        Where Not formInfo Is formInfoToRemove
  381.  
  382.            formInfoToRemove.Enabled = False
  383.            Me.DeassocHandlers(formInfoToRemove.Form)
  384.  
  385.        Else
  386.            Throw New ArgumentException("The specified form is not found.", "form")
  387.  
  388.        End If
  389.  
  390.    End Sub
  391.  
  392.    ''' <summary>
  393.    ''' Finds the <see cref="FormDragInfo"/> instance that is associated with the specified <see cref="Form"/> reference.
  394.    ''' </summary>
  395.    ''' <param name="form">The <see cref="Form"/>.</param>
  396.    ''' <returns>The <see cref="FormDragInfo"/> instance that is associated with the specified <see cref="Form"/> reference.</returns>
  397.    Public Function FindFormDragInfo(ByVal form As Form) As FormDragInfo
  398.  
  399.        Return (From formInfo As FormDragger.FormDragInfo In Me.forms1
  400.                Where formInfo.Form Is form).FirstOrDefault
  401.  
  402.    End Function
  403.  
  404.    ''' <summary>
  405.    ''' Finds the <see cref="FormDragInfo"/> instance that is associated with the specified <see cref="Form"/> reference.
  406.    ''' </summary>
  407.    ''' <param name="name">The <see cref="Form"/> name.</param>
  408.    ''' <returns>The <see cref="FormDragInfo"/> instance that is associated with the specified <see cref="Form"/> reference.</returns>
  409.    Public Function FindFormDragInfo(ByVal name As String,
  410.                                     Optional stringComparison As StringComparison =
  411.                                              StringComparison.OrdinalIgnoreCase) As FormDragInfo
  412.  
  413.        Return (From formInfo As FormDragger.FormDragInfo In Me.forms1
  414.                Where formInfo.Name.Equals(name, stringComparison)).FirstOrDefault
  415.  
  416.    End Function
  417.  
  418. #End Region
  419.  
  420. #Region " Private Methods "
  421.  
  422.    ''' <summary>
  423.    ''' Associates the <see cref="Form"/> handlers to enable draggable operations.
  424.    ''' </summary>
  425.    ''' <param name="form">The form.</param>
  426.    Private Sub AssocHandlers(ByVal form As Form)
  427.  
  428.        AddHandler form.MouseDown, AddressOf Me.Form_MouseDown
  429.        AddHandler form.MouseUp, AddressOf Me.Form_MouseUp
  430.        AddHandler form.MouseMove, AddressOf Me.Form_MouseMove
  431.        AddHandler form.MouseEnter, AddressOf Me.Form_MouseEnter
  432.        AddHandler form.MouseLeave, AddressOf Me.Form_MouseLeave
  433.  
  434.    End Sub
  435.  
  436.    ''' <summary>
  437.    ''' Deassociates the <see cref="Form"/> handlers to disable draggable operations.
  438.    ''' </summary>
  439.    ''' <param name="form">The form.</param>
  440.    Private Sub DeassocHandlers(ByVal form As Form)
  441.  
  442.        If Not form.IsDisposed AndAlso Not form.Disposing Then
  443.  
  444.            RemoveHandler form.MouseDown, AddressOf Me.Form_MouseDown
  445.            RemoveHandler form.MouseUp, AddressOf Me.Form_MouseUp
  446.            RemoveHandler form.MouseMove, AddressOf Me.Form_MouseMove
  447.            RemoveHandler form.MouseEnter, AddressOf Me.Form_MouseEnter
  448.            RemoveHandler form.MouseLeave, AddressOf Me.Form_MouseLeave
  449.  
  450.        End If
  451.  
  452.    End Sub
  453.  
  454.    ''' <summary>
  455.    ''' Return the new location.
  456.    ''' </summary>
  457.    ''' <param name="formInfo">
  458.    ''' The <see cref="FormDragInfo"/> instance
  459.    ''' that contains the <see cref="Form"/> reference and its draggable info.
  460.    ''' </param>
  461.    ''' <param name="mouseCoordinates">The current mouse coordinates.</param>
  462.    ''' <returns>The new location.</returns>
  463.    Private Function GetNewLocation(ByVal formInfo As FormDragInfo,
  464.                                    ByVal mouseCoordinates As Point) As Point
  465.  
  466.        Return New Point(formInfo.InitialLocation.X + (mouseCoordinates.X - formInfo.InitialMouseCoords.X),
  467.                         formInfo.InitialLocation.Y + (mouseCoordinates.Y - formInfo.InitialMouseCoords.Y))
  468.  
  469.    End Function
  470.  
  471. #End Region
  472.  
  473. #Region " Hidden Methods "
  474.  
  475.    ''' <summary>
  476.    ''' Serves as a hash function for a particular type.
  477.    ''' </summary>
  478.    <EditorBrowsable(EditorBrowsableState.Never)>
  479.    Public Shadows Function GetHashCode() As Integer
  480.        Return MyBase.GetHashCode
  481.    End Function
  482.  
  483.    ''' <summary>
  484.    ''' Gets the System.Type of the current instance.
  485.    ''' </summary>
  486.    ''' <returns>The exact runtime type of the current instance.</returns>
  487.    <EditorBrowsable(EditorBrowsableState.Never)>
  488.    Public Shadows Function [GetType]() As Type
  489.        Return MyBase.GetType
  490.    End Function
  491.  
  492.    ''' <summary>
  493.    ''' Determines whether the specified System.Object instances are considered equal.
  494.    ''' </summary>
  495.    <EditorBrowsable(EditorBrowsableState.Never)>
  496.    Public Shadows Function Equals(ByVal obj As Object) As Boolean
  497.        Return MyBase.Equals(obj)
  498.    End Function
  499.  
  500.    ''' <summary>
  501.    ''' Determines whether the specified System.Object instances are the same instance.
  502.    ''' </summary>
  503.    <EditorBrowsable(EditorBrowsableState.Never)>
  504.    Private Shadows Sub ReferenceEquals()
  505.    End Sub
  506.  
  507.    ''' <summary>
  508.    ''' Returns a String that represents the current object.
  509.    ''' </summary>
  510.    <EditorBrowsable(EditorBrowsableState.Never)>
  511.    Public Shadows Function ToString() As String
  512.        Return MyBase.ToString
  513.    End Function
  514.  
  515. #End Region
  516.  
  517. #Region " Event Handlers "
  518.  
  519.    ''' <summary>
  520.    ''' Handles the MouseEnter event of the Form.
  521.    ''' </summary>
  522.    ''' <param name="sender">The source of the event.</param>
  523.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  524.    Private Sub Form_MouseEnter(ByVal sender As Object, ByVal e As EventArgs)
  525.  
  526.        Dim formInfo As FormDragInfo = FindFormDragInfo(DirectCast(sender, Form))
  527.  
  528.        formInfo.OldCursor = formInfo.Form.Cursor
  529.  
  530.        If formInfo.Enabled Then
  531.            formInfo.Form.Cursor = formInfo.Cursor
  532.            ' Optional:
  533.            ' formInfo.Form.BringToFront()
  534.        End If
  535.  
  536.    End Sub
  537.  
  538.    ''' <summary>
  539.    ''' Handles the MouseLeave event of the Form.
  540.    ''' </summary>
  541.    ''' <param name="sender">The source of the event.</param>
  542.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  543.    Private Sub Form_MouseLeave(ByVal sender As Object, ByVal e As EventArgs)
  544.  
  545.        Dim formInfo As FormDragInfo = FindFormDragInfo(DirectCast(sender, Form))
  546.  
  547.        formInfo.Form.Cursor = formInfo.OldCursor
  548.  
  549.    End Sub
  550.  
  551.    ''' <summary>
  552.    ''' Handles the MouseDown event of the Form.
  553.    ''' </summary>
  554.    ''' <param name="sender">The source of the event.</param>
  555.    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
  556.    Private Sub Form_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
  557.  
  558.        Dim formInfo As FormDragInfo = FindFormDragInfo(DirectCast(sender, Form))
  559.  
  560.        If formInfo.Enabled Then
  561.            formInfo.DragInfo = New FormDragger(formInfo, Form.MousePosition, formInfo.Form.Location)
  562.        End If
  563.  
  564.    End Sub
  565.  
  566.    ''' <summary>
  567.    ''' Handles the MouseMove event of the Form.
  568.    ''' </summary>
  569.    ''' <param name="sender">The source of the event.</param>
  570.    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
  571.    Private Sub Form_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs)
  572.  
  573.        Dim formInfo As FormDragInfo = FindFormDragInfo(DirectCast(sender, Form))
  574.  
  575.        If formInfo.Enabled AndAlso (formInfo.DragInfo IsNot FormDragger.Empty) Then
  576.            formInfo.Form.Location = formInfo.DragInfo.GetNewLocation(formInfo, Form.MousePosition)
  577.        End If
  578.  
  579.    End Sub
  580.  
  581.    ''' <summary>
  582.    ''' Handles the MouseUp event of the Form.
  583.    ''' </summary>
  584.    ''' <param name="sender">The source of the event.</param>
  585.    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
  586.    Private Sub Form_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs)
  587.  
  588.        Dim formInfo As FormDragInfo = FindFormDragInfo(DirectCast(sender, Form))
  589.  
  590.        formInfo.DragInfo = FormDragger.Empty
  591.  
  592.    End Sub
  593.  
  594. #End Region
  595.  
  596. #Region " IDisposable "
  597.  
  598.    ''' <summary>
  599.    ''' To detect redundant calls when disposing.
  600.    ''' </summary>
  601.    Private isDisposed As Boolean = False
  602.  
  603.    ''' <summary>
  604.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  605.    ''' </summary>
  606.    Public Sub Dispose() Implements IDisposable.Dispose
  607.        Me.Dispose(True)
  608.        GC.SuppressFinalize(Me)
  609.    End Sub
  610.  
  611.    ''' <summary>
  612.    ''' Releases unmanaged and - optionally - managed resources.
  613.    ''' </summary>
  614.    ''' <param name="IsDisposing">
  615.    ''' <c>true</c> to release both managed and unmanaged resources;
  616.    ''' <c>false</c> to release only unmanaged resources.
  617.    ''' </param>
  618.    Protected Sub Dispose(ByVal isDisposing As Boolean)
  619.  
  620.        If Not Me.isDisposed Then
  621.  
  622.            If isDisposing Then
  623.  
  624.                For Each formInfo As FormDragInfo In Me.forms1
  625.  
  626.                    With formInfo
  627.  
  628.                        .Enabled = False
  629.                        .OldCursor = Nothing
  630.                        .DragInfo = FormDragger.Empty
  631.                        .InitialMouseCoords = Point.Empty
  632.                        .InitialLocation = Point.Empty
  633.  
  634.                        Me.DeassocHandlers(.Form)
  635.  
  636.                    End With ' form
  637.  
  638.                Next formInfo
  639.  
  640.                Me.forms1 = Nothing
  641.  
  642.            End If ' IsDisposing
  643.  
  644.        End If ' Not Me.IsDisposed
  645.  
  646.        Me.isDisposed = True
  647.  
  648.    End Sub
  649.  
  650. #End Region
  651.  
  652. End Class
  653.  
  654. #End Region
« Última modificación: 15 Marzo 2015, 02:26 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #455 en: 20 Marzo 2015, 00:24 am »

Aquí les dejo un (casi)completo set de utilidades para manejar el registro de windows desde una aplicación .Net, tiene todo tipo de funcionalidades.

Ejemplos de uso:
Código
  1. ----------------
  2. Set RegInfo Instance
  3. ----------------
  4.  
  5.    Dim regInfo As New RegEdit.RegInfo
  6.    With regInfo
  7.        .RootKeyName = "HKCU"
  8.        .SubKeyPath = "Subkey Path"
  9.        .ValueName = "Value Name"
  10.        .ValueType = Microsoft.Win32.RegistryValueKind.String
  11.        .ValueData = "Hello World!"
  12.    End With
  13.  
  14.    Dim regInfoByte As New RegEdit.RegInfo(Of Byte())
  15.    With regInfoByte
  16.        .RootKeyName = "HKCU"
  17.        .SubKeyPath = "Subkey Path"
  18.        .ValueName = "Value Name"
  19.        .ValueType = Microsoft.Win32.RegistryValueKind.Binary
  20.        .ValueData = System.Text.Encoding.ASCII.GetBytes("Hello World!")
  21.    End With
  22.  
  23. ----------------
  24. Create SubKey
  25. ----------------
  26.  
  27.    RegEdit.CreateSubKey(fullKeyPath:="HKCU\Subkey Path\")
  28.    RegEdit.CreateSubKey(rootKeyName:="HKCU",
  29.                         subKeyPath:="Subkey Path")
  30.    RegEdit.CreateSubKey(regInfo:=regInfoByte)
  31.  
  32.    Dim regKey1 As Microsoft.Win32.RegistryKey =
  33.        RegEdit.CreateSubKey(fullKeyPath:="HKCU\Subkey Path\",
  34.                             registryKeyPermissionCheck:=Microsoft.Win32.RegistryKeyPermissionCheck.Default,
  35.                             registryOptions:=Microsoft.Win32.RegistryOptions.None)
  36.  
  37.    Dim regKey2 As Microsoft.Win32.RegistryKey =
  38.        RegEdit.CreateSubKey(rootKeyName:="HKCU",
  39.                             subKeyPath:="Subkey Path",
  40.                             registryKeyPermissionCheck:=Microsoft.Win32.RegistryKeyPermissionCheck.Default,
  41.                             registryOptions:=Microsoft.Win32.RegistryOptions.None)
  42.  
  43.    Dim regInfo2 As RegEdit.RegInfo(Of String) = RegEdit.CreateSubKey(Of String)(fullKeyPath:="HKCU\Subkey Path\")
  44.    Dim regInfo3 As RegEdit.RegInfo(Of String) = RegEdit.CreateSubKey(Of String)(rootKeyName:="HKCU",
  45.                                                                                 subKeyPath:="Subkey Path")
  46.  
  47. ----------------
  48. Create Value
  49. ----------------
  50.  
  51.    RegEdit.CreateValue(fullKeyPath:="HKCU\Subkey Path\",
  52.                        valueName:="Value Name",
  53.                        valueData:="Value Data",
  54.                        valueType:=Microsoft.Win32.RegistryValueKind.String)
  55.  
  56.    RegEdit.CreateValue(rootKeyName:="HKCU",
  57.                        subKeyPath:="Subkey Path",
  58.                        valueName:="Value Name",
  59.                        valueData:="Value Data",
  60.                        valueType:=Microsoft.Win32.RegistryValueKind.String)
  61.  
  62.    RegEdit.CreateValue(regInfo:=regInfoByte)
  63.  
  64.    RegEdit.CreateValue(Of String)(fullKeyPath:="HKCU\Subkey Path\",
  65.                                   valueName:="Value Name",
  66.                                   valueData:="Value Data",
  67.                                   valueType:=Microsoft.Win32.RegistryValueKind.String)
  68.  
  69.    RegEdit.CreateValue(Of String)(rootKeyName:="HKCU",
  70.                                   subKeyPath:="Subkey Path",
  71.                                   valueName:="Value Name",
  72.                                   valueData:="Value Data",
  73.                                   valueType:=Microsoft.Win32.RegistryValueKind.String)
  74.  
  75.    RegEdit.CreateValue(Of Byte())(regInfo:=regInfoByte)
  76.  
  77. ----------------
  78. Copy KeyTree
  79. ----------------
  80.  
  81.    RegEdit.CopyKeyTree(sourceFullKeyPath:="HKCU\Source Subkey Path\",
  82.                        targetFullKeyPath:="HKCU\Target Subkey Path\")
  83.  
  84.    RegEdit.CopyKeyTree(sourceRootKeyName:="HKCU",
  85.                        sourceSubKeyPath:="Source Subkey Path\",
  86.                        targetRootKeyName:="HKCU",
  87.                        targetSubKeyPath:="Target Subkey Path\")
  88.  
  89. ----------------
  90. Move KeyTree
  91. ----------------
  92.  
  93.    RegEdit.MoveKeyTree(sourceFullKeyPath:="HKCU\Source Subkey Path\",
  94.                        targetFullKeyPath:="HKCU\Target Subkey Path\")
  95.  
  96.    RegEdit.MoveKeyTree(sourceRootKeyName:="HKCU",
  97.                        sourceSubKeyPath:="Source Subkey Path\",
  98.                        targetRootKeyName:="HKCU",
  99.                        targetSubKeyPath:="Target Subkey Path\")
  100.  
  101. ----------------
  102. Copy SubKeys
  103. ----------------
  104.  
  105.    RegEdit.CopySubKeys(sourceFullKeyPath:="HKCU\Source Subkey Path\",
  106.                        targetFullKeyPath:="HKCU\Target Subkey Path\")
  107.  
  108.    RegEdit.CopySubKeys(sourceRootKeyName:="HKCU",
  109.                        sourceSubKeyPath:="Source Subkey Path\",
  110.                        targetRootKeyName:="HKCU",
  111.                        targetSubKeyPath:="Target Subkey Path\")
  112.  
  113. ----------------
  114. Move SubKeys
  115. ----------------
  116.  
  117.    RegEdit.MoveSubKeys(sourceFullKeyPath:="HKCU\Source Subkey Path\",
  118.                        targetFullKeyPath:="HKCU\Target Subkey Path\")
  119.  
  120.    RegEdit.MoveSubKeys(sourceRootKeyName:="HKCU",
  121.                        sourceSubKeyPath:="Source Subkey Path\",
  122.                        targetRootKeyName:="HKCU",
  123.                        targetSubKeyPath:="Target Subkey Path\")
  124.  
  125. ----------------
  126. Copy Value
  127. ----------------
  128.  
  129.    RegEdit.CopyValue(sourceFullKeyPath:="HKCU\Source Subkey Path\",
  130.                      sourceValueName:="Value Name",
  131.                      targetFullKeyPath:="HKCU\Target Subkey Path\",
  132.                      targetValueName:="Value Name")
  133.  
  134.    RegEdit.CopyValue(sourceRootKeyName:="HKCU",
  135.                      sourceSubKeyPath:="Source Subkey Path\",
  136.                      sourceValueName:="Value Name",
  137.                      targetRootKeyName:="HKCU",
  138.                      targetSubKeyPath:="Target Subkey Path\",
  139.                      targetValueName:="Value Name")
  140.  
  141. ----------------
  142. Move Value
  143. ----------------
  144.  
  145.    RegEdit.MoveValue(sourceFullKeyPath:="HKCU\Source Subkey Path\",
  146.                      sourceValueName:="Value Name",
  147.                      targetFullKeyPath:="HKCU\Target Subkey Path\",
  148.                      targetValueName:="Value Name")
  149.  
  150.    RegEdit.MoveValue(sourceRootKeyName:="HKCU",
  151.                      sourceSubKeyPath:="Source Subkey Path\",
  152.                      sourceValueName:="Value Name",
  153.                      targetRootKeyName:="HKCU",
  154.                      targetSubKeyPath:="Target Subkey Path\",
  155.                      targetValueName:="Value Name")
  156.  
  157. ----------------
  158. DeleteValue
  159. ----------------
  160.  
  161.    RegEdit.DeleteValue(fullKeyPath:="HKCU\Subkey Path\",
  162.                        valueName:="Value Name",
  163.                        throwOnMissingValue:=True)
  164.  
  165.    RegEdit.DeleteValue(rootKeyName:="HKCU",
  166.                        subKeyPath:="Subkey Path",
  167.                        valueName:="Value Name",
  168.                        throwOnMissingValue:=True)
  169.  
  170.    RegEdit.DeleteValue(regInfo:=regInfoByte,
  171.                        throwOnMissingValue:=True)
  172.  
  173. ----------------
  174. Delete SubKey
  175. ----------------
  176.  
  177.    RegEdit.DeleteSubKey(fullKeyPath:="HKCU\Subkey Path\",
  178.                         throwOnMissingSubKey:=False)
  179.  
  180.    RegEdit.DeleteSubKey(rootKeyName:="HKCU",
  181.                         subKeyPath:="Subkey Path",
  182.                         throwOnMissingSubKey:=False)
  183.  
  184.    RegEdit.DeleteSubKey(regInfo:=regInfoByte,
  185.                         throwOnMissingSubKey:=False)
  186.  
  187. ----------------
  188. Exist SubKey?
  189. ----------------
  190.  
  191.    Dim exist1 As Boolean = RegEdit.ExistSubKey(fullKeyPath:="HKCU\Subkey Path\")
  192.  
  193.    Dim exist2 As Boolean = RegEdit.ExistSubKey(rootKeyName:="HKCU",
  194.                                                subKeyPath:="Subkey Path")
  195.  
  196. ----------------
  197. Exist Value?
  198. ----------------
  199.  
  200.    Dim exist3 As Boolean = RegEdit.ExistValue(fullKeyPath:="HKCU\Subkey Path\",
  201.                                               valueName:="Value Name")
  202.  
  203.    Dim exist4 As Boolean = RegEdit.ExistValue(rootKeyName:="HKCU",
  204.                                               subKeyPath:="Subkey Path",
  205.                                               valueName:="Value Name")
  206.  
  207. ----------------
  208. Value Is Empty?
  209. ----------------
  210.  
  211.    Dim isEmpty1 As Boolean = RegEdit.ValueIsEmpty(fullKeyPath:="HKCU\Subkey Path\",
  212.                                                   valueName:="Value Name")
  213.  
  214.    Dim isEmpty2 As Boolean = RegEdit.ValueIsEmpty(rootKeyName:="HKCU",
  215.                                                   subKeyPath:="Subkey Path",
  216.                                                   valueName:="Value Name")
  217.  
  218. ----------------
  219. Export Key
  220. ----------------
  221.  
  222.    RegEdit.ExportKey(fullKeyPath:="HKCU\Subkey Path\",
  223.                      outputFile:="C:\Backup.reg")
  224.  
  225.    RegEdit.ExportKey(rootKeyName:="HKCU",
  226.                      subKeyPath:="Subkey Path",
  227.                      outputFile:="C:\Backup.reg")
  228.  
  229. ----------------
  230. Import RegFile
  231. ----------------
  232.  
  233.    RegEdit.ImportRegFile(regFilePath:="C:\Backup.reg")
  234.  
  235. ----------------
  236. Jump To Key
  237. ----------------
  238.  
  239.    RegEdit.JumpToKey(fullKeyPath:="HKCU\Subkey Path\")
  240.  
  241.    RegEdit.JumpToKey(rootKeyName:="HKCU",
  242.                      subKeyPath:="Subkey Path")
  243.  
  244. ----------------
  245. Find SubKey
  246. ----------------
  247.  
  248.    Dim regInfoSubkeyCol As IEnumerable(Of RegEdit.Reginfo) =
  249.        RegEdit.FindSubKey(rootKeyName:="HKCU",
  250.                           subKeyPath:="Subkey Path",
  251.                           subKeyName:="Subkey Name",
  252.                           matchFullSubKeyName:=False,
  253.                           ignoreCase:=True,
  254.                           searchOption:=IO.SearchOption.AllDirectories)
  255.  
  256.    For Each reg As RegEdit.RegInfo In regInfoSubkeyCol
  257.        Debug.WriteLine(reg.RootKeyName)
  258.        Debug.WriteLine(reg.SubKeyPath)
  259.        Debug.WriteLine(reg.ValueName)
  260.        Debug.WriteLine(reg.ValueData.ToString)
  261.        Debug.WriteLine("")
  262.    Next reg
  263.  
  264. ----------------
  265. Find Value
  266. ----------------
  267.  
  268.    Dim regInfoValueNameCol As IEnumerable(Of RegEdit.Reginfo) =
  269.        RegEdit.FindValue(rootKeyName:="HKCU",
  270.                              subKeyPath:="Subkey Path",
  271.                              valueName:="Value Name",
  272.                              matchFullValueName:=False,
  273.                              ignoreCase:=True,
  274.                              searchOption:=IO.SearchOption.AllDirectories)
  275.  
  276.    For Each reg As RegEdit.RegInfo In regInfoValueNameCol
  277.        Debug.WriteLine(reg.RootKeyName)
  278.        Debug.WriteLine(reg.SubKeyPath)
  279.        Debug.WriteLine(reg.ValueName)
  280.        Debug.WriteLine(reg.ValueData.ToString)
  281.        Debug.WriteLine("")
  282.    Next reg
  283.  
  284. ----------------
  285. Find Value Data
  286. ----------------
  287.  
  288.    Dim regInfoValueDataCol As IEnumerable(Of RegEdit.Reginfo) =
  289.        RegEdit.FindValueData(rootKeyName:="HKCU",
  290.                              subKeyPath:="Subkey Path",
  291.                              valueData:="Value Data",
  292.                              matchFullData:=False,
  293.                              ignoreCase:=True,
  294.                              searchOption:=IO.SearchOption.AllDirectories)
  295.  
  296.    For Each reg As RegEdit.RegInfo In regInfoValueDataCol
  297.        Debug.WriteLine(reg.RootKeyName)
  298.        Debug.WriteLine(reg.SubKeyPath)
  299.        Debug.WriteLine(reg.ValueName)
  300.        Debug.WriteLine(reg.ValueData.ToString)
  301.        Debug.WriteLine("")
  302.    Next reg
  303.  
  304. ----------------
  305. Get...
  306. ----------------
  307.  
  308.    Dim rootKeyName As String = RegEdit.GetRootKeyName(registryPath:="HKCU\Subkey Path\")
  309.    Dim subKeyPath As String = RegEdit.GetSubKeyPath(registryPath:="HKCU\Subkey Path\")
  310.    Dim rootKey As Microsoft.Win32.RegistryKey = RegEdit.GetRootKey(registryPath:="HKCU\Subkey Path\")
  311.  
  312. ----------------
  313. Get Value Data
  314. ----------------
  315.  
  316.    Dim dataObject As Object = RegEdit.GetValueData(rootKeyName:="HKCU",
  317.                                                    subKeyPath:="Subkey Path",
  318.                                                    valueName:="Value Name")
  319.  
  320.    Dim dataString As String = RegEdit.GetValueData(Of String)(fullKeyPath:="HKCU\Subkey Path\",
  321.                                                               valueName:="Value Name",
  322.                                                               registryValueOptions:=Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames)
  323.  
  324.    Dim dataByte As Byte() = RegEdit.GetValueData(Of Byte())(regInfo:=regInfoByte,
  325.                                                             registryValueOptions:=Microsoft.Win32.RegistryValueOptions.None)
  326.    Debug.WriteLine("dataByte=" & String.Join(",", dataByte))
  327.  
  328. -----------------
  329. Set UserAccessKey
  330. -----------------
  331.  
  332. RegEdit.SetUserAccessKey(fullKeyPath:="HKCU\Subkey Path",
  333.                         userAccess:={RegEdit.ReginiUserAccess.AdministratorsFullAccess})
  334.  
  335. RegEdit.SetUserAccessKey(rootKeyName:="HKCU",
  336.                         subKeyPath:="Subkey Path",
  337.                         userAccess:={RegEdit.ReginiUserAccess.AdministratorsFullAccess,
  338.                                      RegEdit.ReginiUserAccess.CreatorFullAccess,
  339.                                      RegEdit.ReginiUserAccess.SystemFullAccess})


Código fuente:
http://pastebin.com/cNM1j8Uh

Saludos!
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #456 en: 26 Marzo 2015, 11:35 am »

Este snippet sirve para añadir o eliminar de forma muuuuuy sencilla :P un archivo/aplicación al Startup de Windows mediante el registro, con características interesantes...

Modo de empleo:
Código
  1. WinStartupUtil.Add(UserType.CurrentUser, StartupType.Run, KeyBehavior.System32,
  2.                   title:="Application Title",
  3.                   filePath:="C:\Application.exe",
  4.                   arguments:="/Arguments",
  5.                   secureModeByPass:=True)

Código
  1. WinStartupUtil.Remove(UserType.CurrentUser, StartupType.Run, KeyBehavior.System32,
  2.                      title:="Application Title",
  3.                      throwOnMissingValue:=True)


Source:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 25-March-2015
  4. ' ***********************************************************************
  5. ' <copyright file="WinStartupUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'WinStartupUtil.Add(WinStartupUtil.UserType.CurrentUser,
  13. '                   WinStartupUtil.StartupType.Run,
  14. '                   WinStartupUtil.KeyBehavior.System32,
  15. '                   title:="Application Title",
  16. '                   filePath:="C:\Application.exe",
  17. '                   secureModeByPass:=True)
  18.  
  19. 'WinStartupUtil.Remove(WinStartupUtil.UserType.CurrentUser,
  20. '                      WinStartupUtil.StartupType.Run,
  21. '                      WinStartupUtil.KeyBehavior.System32,
  22. '                      title:="Application Title",
  23. '                      throwOnMissingValue:=True)
  24.  
  25. #End Region
  26.  
  27. #Region " Option Statements "
  28.  
  29. Option Explicit On
  30. Option Strict On
  31. Option Infer Off
  32.  
  33. #End Region
  34.  
  35. #Region " Imports "
  36.  
  37. Imports Microsoft.Win32
  38.  
  39. #End Region
  40.  
  41. #Region " WinStartupUtil "
  42.  
  43.  
  44. ''' <summary>
  45. ''' Adds or removes an application to Windows Startup.
  46. ''' </summary>
  47. Public NotInheritable Class WinStartupUtil
  48.  
  49. #Region " Properties "
  50.  
  51.    ''' <summary>
  52.    ''' Gets the 'Run' registry subkey path.
  53.    ''' </summary>
  54.    ''' <value>The 'Run' registry subkey path.</value>
  55.    Public Shared ReadOnly Property RunSubKeyPath As String
  56.        Get
  57.            Return "Software\Microsoft\Windows\CurrentVersion\Run"
  58.        End Get
  59.    End Property
  60.  
  61.    ''' <summary>
  62.    ''' Gets the 'Run' registry subkey path for x86 appications on x64 operating system.
  63.    ''' </summary>
  64.    ''' <value>The 'Run' registry subkey path for x86 appications on x64 operating system.</value>
  65.    Public Shared ReadOnly Property RunSubKeyPathSysWow64 As String
  66.        Get
  67.            Return "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"
  68.        End Get
  69.    End Property
  70.  
  71.    ''' <summary>
  72.    ''' Gets the 'RunOnce' registry subkey path.
  73.    ''' </summary>
  74.    ''' <value>The 'RunOnce' registry subkey path.</value>
  75.    Public Shared ReadOnly Property RunOnceSubKeyPath As String
  76.        Get
  77.            Return "Software\Microsoft\Windows\CurrentVersion\RunOnce"
  78.        End Get
  79.    End Property
  80.  
  81.    ''' <summary>
  82.    ''' Gets the 'RunOnce' registry subkey path for x86 appications on x64 operating system.
  83.    ''' </summary>
  84.    ''' <value>The 'RunOnce' registry subkey path for x86 appications on x64 operating system.</value>
  85.    Public Shared ReadOnly Property RunOnceSubKeyPathSysWow64 As String
  86.        Get
  87.            Return "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\RunOnce"
  88.        End Get
  89.    End Property
  90.  
  91. #End Region
  92.  
  93. #Region " Enumerations "
  94.  
  95.    ''' <summary>
  96.    ''' Specifies an user type.
  97.    ''' </summary>
  98.    Public Enum UserType As Integer
  99.  
  100.        ''' <summary>
  101.        ''' 'HKEY_CURRENT_USER' root key.
  102.        ''' </summary>
  103.        CurrentUser = &H1
  104.  
  105.        ''' <summary>
  106.        ''' 'HKEY_LOCAL_MACHINE' root key.
  107.        ''' </summary>
  108.        AllUsers = &H2
  109.  
  110.    End Enum
  111.  
  112.    ''' <summary>
  113.    ''' Specifies a Startup type.
  114.    ''' </summary>
  115.    Public Enum StartupType As Integer
  116.  
  117.        ''' <summary>
  118.        ''' 'Run' registry subkey.
  119.        ''' </summary>
  120.        Run = &H1
  121.  
  122.        ''' <summary>
  123.        ''' 'RunOnce' registry subkey.
  124.        ''' </summary>
  125.        RunOnce = &H2
  126.  
  127.    End Enum
  128.  
  129.    ''' <summary>
  130.    ''' Specifies a registry key behavior.
  131.    ''' </summary>
  132.    Public Enum KeyBehavior As Integer
  133.  
  134.        ''' <summary>
  135.        ''' System32 registry subkey.
  136.        ''' </summary>
  137.        System32 = &H1
  138.  
  139.        ''' <summary>
  140.        ''' SysWow64 registry subkey.
  141.        ''' </summary>
  142.        SysWow64 = &H2
  143.  
  144.    End Enum
  145.  
  146. #End Region
  147.  
  148. #Region " Public Methods "
  149.  
  150.    ''' <summary>
  151.    ''' Adds an application to Windows Startup.
  152.    ''' </summary>
  153.    ''' <param name="userType">The type of user.</param>
  154.    ''' <param name="startupType">The type of startup.</param>
  155.    ''' <param name="keyBehavior">The registry key behavior.</param>
  156.    ''' <param name="title">The registry value title.</param>
  157.    ''' <param name="filePath">The application file path.</param>
  158.    ''' <param name="secureModeByPass">
  159.    ''' If set to <c>true</c>, the file is ran even when the user logs into 'Secure Mode' on Windows.
  160.    ''' </param>
  161.    ''' <exception cref="System.ArgumentNullException">title or filePath</exception>
  162.    Public Shared Sub Add(ByVal userType As UserType,
  163.                          ByVal startupType As StartupType,
  164.                          ByVal keyBehavior As KeyBehavior,
  165.                          ByVal title As String,
  166.                          ByVal filePath As String,
  167.                          Optional ByVal arguments As String = "",
  168.                          Optional secureModeByPass As Boolean = False)
  169.  
  170.        If String.IsNullOrEmpty(title) Then
  171.            Throw New ArgumentNullException("title")
  172.  
  173.        ElseIf String.IsNullOrEmpty(filePath) Then
  174.            Throw New ArgumentNullException("filePath")
  175.  
  176.        Else
  177.            If secureModeByPass Then
  178.                title = title.Insert(0, "*")
  179.            End If
  180.  
  181.            Dim regKey As RegistryKey = Nothing
  182.            Try
  183.                regKey = GetRootKey(userType).OpenSubKey(GetSubKeyPath(startupType, keyBehavior), writable:=True)
  184.                regKey.SetValue(title, String.Format("""{0}"" {1}", filePath, arguments), RegistryValueKind.String)
  185.  
  186.            Catch ex As Exception
  187.                Throw
  188.  
  189.            Finally
  190.                If regKey IsNot Nothing Then
  191.                    regKey.Close()
  192.                End If
  193.  
  194.            End Try
  195.  
  196.        End If
  197.  
  198.    End Sub
  199.  
  200.    ''' <summary>
  201.    ''' Removes an application from Windows Startup.
  202.    ''' </summary>
  203.    ''' <param name="userType">The type of user.</param>
  204.    ''' <param name="startupType">The type of startup.</param>
  205.    ''' <param name="keyBehavior">The registry key behavior.</param>
  206.    ''' <param name="title">The value name to find.</param>
  207.    ''' <param name="throwOnMissingValue">if set to <c>true</c>, throws an exception on missing value.</param>
  208.    ''' <exception cref="System.ArgumentNullException">title</exception>
  209.    ''' <exception cref="System.ArgumentException">Registry value not found.;title</exception>
  210.    Friend Shared Sub Remove(ByVal userType As UserType,
  211.                             ByVal startupType As StartupType,
  212.                             ByVal keyBehavior As KeyBehavior,
  213.                             ByVal title As String,
  214.                             Optional ByVal throwOnMissingValue As Boolean = False)
  215.  
  216.        If String.IsNullOrEmpty(title) Then
  217.            Throw New ArgumentNullException("title")
  218.  
  219.        Else
  220.            Dim valueName As String = String.Empty
  221.            Dim regKey As RegistryKey = Nothing
  222.  
  223.            Try
  224.                regKey = GetRootKey(userType).OpenSubKey(GetSubKeyPath(startupType, keyBehavior), writable:=True)
  225.  
  226.                If regKey.GetValue(title, defaultValue:=Nothing) IsNot Nothing Then
  227.                    valueName = title
  228.  
  229.                ElseIf regKey.GetValue(title.Insert(0, "*"), defaultValue:=Nothing) IsNot Nothing Then
  230.                    valueName = title.Insert(0, "*")
  231.  
  232.                Else
  233.                    If throwOnMissingValue Then
  234.                        Throw New ArgumentException("Registry value not found.", "title")
  235.                    End If
  236.  
  237.                End If
  238.  
  239.                regKey.DeleteValue(valueName, throwOnMissingValue:=throwOnMissingValue)
  240.  
  241.            Catch ex As Exception
  242.                Throw
  243.  
  244.            Finally
  245.                If regKey IsNot Nothing Then
  246.                    regKey.Close()
  247.                End If
  248.  
  249.            End Try
  250.  
  251.        End If
  252.  
  253.    End Sub
  254.  
  255. #End Region
  256.  
  257. #Region " Private Methods "
  258.  
  259.    ''' <summary>
  260.    ''' Gets a <see cref="RegistryKey"/> instance of the specified root key.
  261.    ''' </summary>
  262.    ''' <param name="userType">The type of user.</param>
  263.    ''' <returns>A <see cref="RegistryKey"/> instance of the specified root key.</returns>
  264.    ''' <exception cref="System.ArgumentException">Invalid enumeration value.;userType</exception>
  265.    Private Shared Function GetRootKey(ByVal userType As UserType) As RegistryKey
  266.  
  267.        Select Case userType
  268.  
  269.            Case userType.CurrentUser
  270.                Return Registry.CurrentUser
  271.  
  272.            Case userType.AllUsers
  273.                Return Registry.LocalMachine
  274.  
  275.            Case Else
  276.                Throw New ArgumentException("Invalid enumeration value.", "userType")
  277.  
  278.        End Select ' userType
  279.  
  280.    End Function
  281.  
  282.    ''' <summary>
  283.    ''' Gets the proper registry subkey path from the parameters criteria.
  284.    ''' </summary>
  285.    ''' <param name="startupType">Type of the startup.</param>
  286.    ''' <param name="keyBehavior">The key behavior.</param>
  287.    ''' <returns>The registry subkey path.</returns>
  288.    ''' <exception cref="System.ArgumentException">
  289.    ''' Invalid enumeration value.;startupType or
  290.    ''' Invalid enumeration value.;keyBehavior
  291.    ''' </exception>
  292.    Private Shared Function GetSubKeyPath(ByVal startupType As StartupType,
  293.                                          ByVal keyBehavior As KeyBehavior) As String
  294.  
  295.        Select Case keyBehavior
  296.  
  297.            Case keyBehavior.System32
  298.  
  299.                Select Case startupType
  300.  
  301.                    Case startupType.Run
  302.                        Return RunSubKeyPath
  303.  
  304.                    Case startupType.RunOnce
  305.                        Return RunOnceSubKeyPath
  306.  
  307.                    Case Else
  308.                        Throw New ArgumentException("Invalid enumeration value.", "startupType")
  309.  
  310.                End Select ' startupType
  311.  
  312.            Case keyBehavior.SysWow64
  313.  
  314.                Select Case startupType
  315.  
  316.                    Case startupType.Run
  317.                        Return RunSubKeyPathSysWow64
  318.  
  319.                    Case startupType.RunOnce
  320.                        Return RunOnceSubKeyPathSysWow64
  321.  
  322.                    Case Else
  323.                        Throw New ArgumentException("Invalid enumeration value.", "startupType")
  324.  
  325.                End Select ' startupType
  326.  
  327.            Case Else
  328.                Throw New ArgumentException("Invalid enumeration value.", "keyBehavior")
  329.  
  330.        End Select ' keyBehavior
  331.  
  332.    End Function
  333.  
  334. #End Region
  335.  
  336. End Class
  337.  
  338. #End Region
« Última modificación: 26 Marzo 2015, 11:45 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #457 en: 7 Abril 2015, 10:19 am »

El siguiente snippet sirve para "redondear" una cantidad de bytes a la unidad de tamaño más apróximada, con soporte para precisión decimal y formato personalizado.

Ejemplo de uso:
Código
  1.        For Each unit As RoundByteInfo.SizeUnit In [Enum].GetValues(GetType(RoundByteInfo.SizeUnit))
  2.  
  3.            Dim rByteInfo As New RoundByteInfo(unit)
  4.            Dim stringFormat As String = String.Format("{0} Bytes rounded to {1} {2}.",
  5.                                                       rByteInfo.ByteValue(CultureInfo.CurrentCulture.NumberFormat),
  6.                                                       rByteInfo.RoundedValue(decimalPrecision:=2, numberFormatInfo:=Nothing),
  7.                                                       rByteInfo.UnitLongName)
  8.  
  9.            Debug.WriteLine(stringFormat)
  10.  
  11.        Next unit

Output:
Código:
1 Bytes rounded to 1,00 Bytes.
1.024 Bytes rounded to 1,00 KiloBytes.
1.048.576 Bytes rounded to 1,00 MegaBytes.
1.073.741.824 Bytes rounded to 1,00 GigaBytes.
1.099.511.627.776 Bytes rounded to 1,00 TeraBytes.
1.125.899.906.842.620 Bytes rounded to 1,00 PetaBytes.

Source:
Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 07-April-2015
  4. ' ***********************************************************************
  5. ' <copyright file="RoundByteInfo.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'For Each unit As RoundByteInfo.SizeUnit In [Enum].GetValues(GetType(RoundByteInfo.SizeUnit))
  13. '
  14. '    Dim rByteInfo As New RoundByteInfo(unit)
  15. '    Dim stringFormat As String = String.Format("{0} Bytes rounded to {1} {2}.",
  16. '                                               rByteInfo.ByteValue,
  17. '                                               rByteInfo.RoundedValue(decimalPrecision:=2),
  18. '                                               rByteInfo.UnitLongName)
  19. '    Debug.WriteLine(stringFormat)
  20. '
  21. 'Next unit
  22.  
  23. #End Region
  24.  
  25. #Region " Option Statements "
  26.  
  27. Option Explicit On
  28. Option Strict On
  29. Option Infer Off
  30.  
  31. #End Region
  32.  
  33. #Region " Imports "
  34.  
  35. Imports System.Globalization
  36.  
  37. #End Region
  38.  
  39. #Region " RoundByteInfo "
  40.  
  41. ''' <summary>
  42. ''' Rounds the specified byte value to its most approximated size unit.
  43. ''' </summary>
  44. Public NotInheritable Class RoundByteInfo
  45.  
  46. #Region " Properties "
  47.  
  48.    ''' <summary>
  49.    ''' Gets the byte value.
  50.    ''' </summary>
  51.    ''' <value>The byte value.</value>
  52.    Public ReadOnly Property ByteValue As Double
  53.        Get
  54.            Return Me.byteValue1
  55.        End Get
  56.    End Property
  57.  
  58.    ''' <summary>
  59.    ''' Gets the byte value.
  60.    ''' </summary>
  61.    ''' <param name="numberFormatInfo">A custom <see cref="NumberFormatInfo"/> format provider.</param>
  62.    ''' <value>The byte value.</value>
  63.    Public ReadOnly Property ByteValue(ByVal numberFormatInfo As NumberFormatInfo) As String
  64.        Get
  65.            If numberFormatInfo Is Nothing Then
  66.                numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
  67.            End If
  68.            Return Me.byteValue1.ToString("N0", numberFormatInfo)
  69.        End Get
  70.    End Property
  71.  
  72.    ''' <summary>
  73.    ''' Gets the rounded byte value.
  74.    ''' </summary>
  75.    ''' <value>The rounded byte value.</value>
  76.    Public ReadOnly Property RoundedValue As Double
  77.        Get
  78.            Return Me.roundedValue1
  79.        End Get
  80.    End Property
  81.  
  82.    ''' <summary>
  83.    ''' Gets the rounded value with the specified decimal precision.
  84.    ''' </summary>
  85.    ''' <param name="decimalPrecision">The numeric decimal precision.</param>
  86.    ''' <param name="numberFormatInfo">A custom <see cref="NumberFormatInfo"/> format provider.</param>
  87.    ''' <value>The rounded value with the specified decimal precision.</value>
  88.    Public ReadOnly Property RoundedValue(ByVal decimalPrecision As Integer,
  89.                                          Optional ByVal numberFormatInfo As NumberFormatInfo = Nothing) As String
  90.        Get
  91.            If numberFormatInfo Is Nothing Then
  92.                numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
  93.            End If
  94.            Return Me.roundedValue1.ToString("N" & decimalPrecision, numberFormatInfo)
  95.        End Get
  96.    End Property
  97.  
  98.    ''' <summary>
  99.    ''' Gets the rounded <see cref="SizeUnit"/>.
  100.    ''' </summary>
  101.    ''' <value>The rounded <see cref="SizeUnit"/>.</value>
  102.    Public ReadOnly Property Unit As SizeUnit
  103.        Get
  104.            Return Me.unit1
  105.        End Get
  106.    End Property
  107.  
  108.    ''' <summary>
  109.    ''' Gets the rounded <see cref="SizeUnit"/> short name.
  110.    ''' </summary>
  111.    ''' <value>The rounded <see cref="SizeUnit"/> short name.</value>
  112.    Public ReadOnly Property UnitShortName As String
  113.        Get
  114.            Return Me.unitShortName1
  115.        End Get
  116.    End Property
  117.  
  118.    ''' <summary>
  119.    ''' Gets the rounded <see cref="SizeUnit"/> long name.
  120.    ''' </summary>
  121.    ''' <value>The rounded <see cref="SizeUnit"/> long name.</value>
  122.    Public ReadOnly Property UnitLongName As String
  123.        Get
  124.            Return Me.unitLongName1
  125.        End Get
  126.    End Property
  127.  
  128.    ''' <summary>
  129.    ''' The byte value.
  130.    ''' </summary>
  131.    Private byteValue1 As Double
  132.  
  133.    ''' <summary>
  134.    ''' The rounded value.
  135.    ''' </summary>
  136.    Private roundedValue1 As Double
  137.  
  138.    ''' <summary>
  139.    ''' The rounded <see cref="SizeUnit"/>.
  140.    ''' </summary>
  141.    Private unit1 As SizeUnit
  142.  
  143.    ''' <summary>
  144.    ''' The rounded <see cref="SizeUnit"/> short name.
  145.    ''' </summary>
  146.    Private unitShortName1 As String
  147.  
  148.    ''' <summary>
  149.    ''' The rounded <see cref="SizeUnit"/> long name.
  150.    ''' </summary>
  151.    Private unitLongName1 As String
  152.  
  153. #End Region
  154.  
  155. #Region " Enumerations "
  156.  
  157.    ''' <summary>
  158.    ''' Specifies a size unit.
  159.    ''' </summary>
  160.    Public Enum SizeUnit As Long
  161.  
  162.        ''' <summary>
  163.        ''' 1 Byte (or 8 bits).
  164.        ''' </summary>
  165.        [Byte] = 1L
  166.  
  167.        ''' <summary>
  168.        ''' Byte-length of 1 KiloByte.
  169.        ''' </summary>
  170.        KiloByte = [Byte] * 1024L
  171.  
  172.        ''' <summary>
  173.        ''' Byte-length of 1 MegaByte.
  174.        ''' </summary>
  175.        MegaByte = KiloByte * KiloByte
  176.  
  177.        ''' <summary>
  178.        ''' Byte-length of 1 GigaByte.
  179.        ''' </summary>
  180.        GigaByte = KiloByte * MegaByte
  181.  
  182.        ''' <summary>
  183.        ''' Byte-length of 1 TeraByte.
  184.        ''' </summary>
  185.        TeraByte = KiloByte * GigaByte
  186.  
  187.        ''' <summary>
  188.        ''' Byte-length of 1 PetaByte.
  189.        ''' </summary>
  190.        PetaByte = KiloByte * TeraByte
  191.  
  192.    End Enum
  193.  
  194. #End Region
  195.  
  196. #Region " Constructors "
  197.  
  198.    ''' <summary>
  199.    ''' Initializes a new instance of the <see cref="RoundByteInfo"/> class.
  200.    ''' </summary>
  201.    ''' <param name="bytes">The byte value.</param>
  202.    ''' <exception cref="System.ArgumentException">Value should be greater than 0.;bytes</exception>
  203.    Public Sub New(ByVal bytes As Double)
  204.  
  205.        If bytes <= 0L Then
  206.            Throw New ArgumentException("Value should be greater than 0.", "bytes")
  207.        Else
  208.            Me.SetRoundByte(bytes)
  209.  
  210.        End If
  211.  
  212.    End Sub
  213.  
  214.    ''' <summary>
  215.    ''' Prevents a default instance of the <see cref="RoundByteInfo"/> class from being created.
  216.    ''' </summary>
  217.    Private Sub New()
  218.    End Sub
  219.  
  220. #End Region
  221.  
  222. #Region " Private Methods "
  223.  
  224.    ''' <summary>
  225.    ''' Rounds the specified byte value to its most approximated <see cref="SizeUnit"/>.
  226.    ''' </summary>
  227.    ''' <param name="bytes">The byte value.</param>
  228.    Private Sub SetRoundByte(ByVal bytes As Double)
  229.  
  230.        Me.byteValue1 = bytes
  231.  
  232.        Select Case bytes
  233.  
  234.            Case Is >= SizeUnit.PetaByte
  235.                Me.roundedValue1 = bytes / SizeUnit.PetaByte
  236.                Me.unit1 = SizeUnit.PetaByte
  237.                Me.unitShortName1 = "PB"
  238.                Me.unitLongName1 = "PetaBytes"
  239.  
  240.            Case Is >= SizeUnit.TeraByte
  241.                Me.roundedValue1 = bytes / SizeUnit.TeraByte
  242.                Me.unit1 = SizeUnit.TeraByte
  243.                Me.unitShortName1 = "TB"
  244.                Me.unitLongName1 = "TeraBytes"
  245.  
  246.            Case Is >= SizeUnit.GigaByte
  247.                Me.roundedValue1 = bytes / SizeUnit.GigaByte
  248.                Me.unit1 = SizeUnit.GigaByte
  249.                Me.unitShortName1 = "GB"
  250.                Me.unitLongName1 = "GigaBytes"
  251.  
  252.            Case Is >= SizeUnit.MegaByte
  253.                Me.roundedValue1 = bytes / SizeUnit.MegaByte
  254.                Me.unit1 = SizeUnit.MegaByte
  255.                Me.unitShortName1 = "MB"
  256.                Me.unitLongName1 = "MegaBytes"
  257.  
  258.            Case Is >= SizeUnit.KiloByte
  259.                Me.roundedValue1 = bytes / SizeUnit.KiloByte
  260.                Me.unit1 = SizeUnit.KiloByte
  261.                Me.unitShortName1 = "KB"
  262.                Me.unitLongName1 = "KiloBytes"
  263.  
  264.            Case Is >= SizeUnit.Byte, Is <= 0
  265.                Me.roundedValue1 = bytes / SizeUnit.Byte
  266.                Me.unit1 = SizeUnit.Byte
  267.                Me.unitShortName1 = "Bytes"
  268.                Me.unitLongName1 = "Bytes"
  269.  
  270.        End Select
  271.  
  272.    End Sub
  273.  
  274. #End Region
  275.  
  276. End Class
  277.  
  278. #End Region
« Última modificación: 7 Abril 2015, 10:23 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #458 en: 11 Abril 2015, 13:38 pm »

Una simple función que publiqué en S.O para cifrar/descifrar un String mediante la técnica de Caesar.

Ejemplo de uso:
Código
  1.        Dim value As String = "Hello World!"
  2.  
  3.        Dim encrypted As String = CaesarEncrypt(value, shift:=15)
  4.        Dim decrypted As String = CaesarDecrypt(encrypted, shift:=15)
  5.  
  6.        Debug.WriteLine(String.Format("Unmodified string: {0}", value))
  7.        Debug.WriteLine(String.Format("Encrypted  string: {0}", encrypted))
  8.        Debug.WriteLine(String.Format("Decrypted  string: {0}", decrypted))

Source:
Código
  1.    ''' <summary>
  2.    ''' Encrypts a string using Caesar's substitution technique.
  3.    ''' </summary>
  4.    ''' <remarks> http://en.wikipedia.org/wiki/Caesar_cipher </remarks>
  5.    ''' <param name="text">The text to encrypt.</param>
  6.    ''' <param name="shift">The character shifting.</param>
  7.    ''' <param name="charSet">A set of character to use in encoding.</param>
  8.    ''' <returns>The encrypted string.</returns>
  9.    Public Shared Function CaesarEncrypt(ByVal text As String,
  10.                                         ByVal shift As Integer,
  11.                                         Optional ByVal charSet As String =
  12.                                                        "abcdefghijklmnopqrstuvwxyz" &
  13.                                                        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" &
  14.                                                        "0123456789" &
  15.                                                        "çñáéíóúàèìòùäëïöü" &
  16.                                                        "ÇÑÁÉÍÓÚÀÈÌÒÙÄËÏÖÜ" &
  17.                                                        " ,;.:-_´¨{`^[+*]ºª\!|""#$~%€&¬/()=?¿'¡}*") As String
  18.  
  19.        Dim sb As New System.Text.StringBuilder With {.Capacity = text.Length}
  20.  
  21.        For Each c As Char In text
  22.  
  23.            Dim charIndex As Integer = charSet.IndexOf(c)
  24.  
  25.            If charIndex = -1 Then
  26.                Throw New ArgumentException(String.Format("Character '{0}' not found in character set '{1}'.", c, charSet), "charSet")
  27.  
  28.            Else
  29.                Do Until (charIndex + shift) < (charSet.Length)
  30.                    charIndex -= charSet.Length
  31.                Loop
  32.  
  33.                sb.Append(charSet(charIndex + shift))
  34.  
  35.            End If
  36.  
  37.        Next c
  38.  
  39.        Return sb.ToString
  40.  
  41.    End Function
  42.  
  43.    ''' <summary>
  44.    ''' Decrypts a string using Caesar's substitution technique.
  45.    ''' </summary>
  46.    ''' <remarks> http://en.wikipedia.org/wiki/Caesar_cipher </remarks>
  47.    ''' <param name="text">The encrypted text to decrypt.</param>
  48.    ''' <param name="shift">The character shifting to reverse the encryption.</param>
  49.    ''' <param name="charSet">A set of character to use in decoding.</param>
  50.    ''' <returns>The decrypted string.</returns>
  51.    Public Shared Function CaesarDecrypt(ByVal text As String,
  52.                                         ByVal shift As Integer,
  53.                                         Optional ByVal charSet As String =
  54.                                                        "abcdefghijklmnopqrstuvwxyz" &
  55.                                                        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" &
  56.                                                        "0123456789" &
  57.                                                        "çñáéíóúàèìòùäëïöü" &
  58.                                                        "ÇÑÁÉÍÓÚÀÈÌÒÙÄËÏÖÜ" &
  59.                                                        " ,;.:-_´¨{`^[+*]ºª\!|""#$~%€&¬/()=?¿'¡}*") As String
  60.  
  61.        Return CaesarEncrypt(text, shift, String.Join("", charSet.Reverse))
  62.  
  63.    End Function
« Última modificación: 11 Abril 2015, 13:41 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #459 en: 11 Abril 2015, 15:05 pm »

Transformar una imagen a blanco y negro:

Código
  1.    ''' <summary>
  2.    ''' Transforms an image to black and white.
  3.    ''' </summary>
  4.    ''' <param name="img">The image.</param>
  5.    ''' <returns>The black and white image.</returns>
  6.    Public Shared Function GetBlackAndWhiteImage(ByVal img As Image) As Image
  7.  
  8.        Dim bmp As Bitmap = New Bitmap(img.Width, img.Height)
  9.  
  10.        Dim grayMatrix As New System.Drawing.Imaging.ColorMatrix(
  11.            {
  12.                New Single() {0.299F, 0.299F, 0.299F, 0, 0},
  13.                New Single() {0.587F, 0.587F, 0.587F, 0, 0},
  14.                New Single() {0.114F, 0.114F, 0.114F, 0, 0},
  15.                New Single() {0, 0, 0, 1, 0},
  16.                New Single() {0, 0, 0, 0, 1}
  17.            })
  18.  
  19.        Using g As Graphics = Graphics.FromImage(bmp)
  20.  
  21.            Using ia As System.Drawing.Imaging.ImageAttributes = New System.Drawing.Imaging.ImageAttributes()
  22.  
  23.                ia.SetColorMatrix(grayMatrix)
  24.                ia.SetThreshold(0.5)
  25.  
  26.                g.DrawImage(img, New Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height,
  27.                                                 GraphicsUnit.Pixel, ia)
  28.  
  29.            End Using
  30.  
  31.        End Using
  32.  
  33.        Return bmp
  34.  
  35.    End Function
En línea



Páginas: 1 ... 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 [46] 47 48 49 50 51 52 53 54 55 56 57 58 59 60 Ir Arriba Respuesta Imprimir 

Ir a:  

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