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

 

 


Tema destacado: Arreglado, de nuevo, el registro del warzone (wargame) de EHN


+  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 5 Visitantes están viendo este tema.
Páginas: 1 ... 26 27 28 29 30 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 ... 60 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 529,050 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #400 en: 3 Agosto 2014, 09:02 am »

Contiene métodos para enumerar los símbolos de una librería externa, como por ejemplo las funciones publicas, algo parecido a lo que hace la aplicación 'DLL Export Viewer': http://www.nirsoft.net/utils/dll_export_viewer.html

Nota: Como dato de interés, algo que yo también me pregunté en su momento:
         No existe ingeniería inversa posible para obtener las firmas de los métodos, los datatypes de los parámetros.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 05-03-2014
  4. ' ***********************************************************************
  5. ' <copyright file="Symbols.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Private Sub Test() Handles MyBase.Load
  13.  
  14. '    Dim dll As String = "C:\C++ lib x64.dll"
  15. '    Dim initialized As Boolean = False
  16. '    Dim hProcess As IntPtr = Nothing
  17.  
  18. '    Try
  19. '        hProcess = Process.GetCurrentProcess().Handle
  20.  
  21. '        If (Symbols.SymInitialize(hProcess, Nothing, True)) Then
  22. '            initialized = True
  23. '        Else
  24. '            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
  25. '        End If
  26.  
  27. '        Dim baseOfDll As IntPtr = Symbols.SymLoadModuleEx(hProcess, IntPtr.Zero, dll,
  28. '                                                          Nothing, 0, 0, IntPtr.Zero,
  29. '                                                          Symbols.SymLoadModuleFlags.Module_And_Symbols)
  30.  
  31. '        If (baseOfDll = IntPtr.Zero) Then
  32. '            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
  33. '        End If
  34.  
  35. '        If Not Symbols.SymEnumSymbols(
  36. '            hProcess,
  37. '            baseOfDll,
  38. '            "*",
  39. '            AddressOf EnumSymProc, IntPtr.Zero
  40. '        ) Then
  41. '            Throw New System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error())
  42. '        End If
  43.  
  44. '    Catch ex As Exception
  45. '        Debug.WriteLine(ex.Message)
  46. '    Finally
  47. '        If (initialized) Then
  48. '            Symbols.SymCleanup(hProcess)
  49. '        End If
  50. '    End Try
  51.  
  52. 'End Sub
  53.  
  54. 'Friend Shared Function EnumSymProc(ByVal pSymInfo As IntPtr,
  55. '                                   ByVal SymbolSize As UInteger,
  56. '                                   ByVal UserContext As IntPtr) As Boolean
  57.  
  58. '    Dim Symbol As New Symbols.SYMBOL_INFO With
  59. '        {
  60. '            .SizeOfStruct = System.Runtime.InteropServices.Marshal.SizeOf(GetType(Symbols.SYMBOL_INFO))
  61. '        }
  62.  
  63. '    System.Runtime.InteropServices.Marshal.PtrToStructure(pSymInfo, Symbol)
  64.  
  65. '    Dim sb As New System.Text.StringBuilder
  66.  
  67. '    With sb
  68.  
  69. '        .AppendLine(String.Format("Address: {0}", CStr(Symbol.Address)))
  70. '        .AppendLine(String.Format("Flags: {0}", Symbol.Flags.ToString))
  71. '        .AppendLine(String.Format("Index: {0}", CStr(Symbol.Index)))
  72. '        .AppendLine(String.Format("Module Base Address: {0}", CStr(Symbol.ModBase)))
  73. '        .AppendLine(String.Format("Name: {0}", Symbol.Name))
  74. '        .AppendLine(String.Format("Size: {0}", CStr(Symbol.Size)))
  75. '        .AppendLine(String.Format("Tag: {0}", Symbol.Tag.ToString))
  76.  
  77. '    End With
  78.  
  79. '    Debug.WriteLine(sb.ToString)
  80.  
  81. '    Return True
  82.  
  83. 'End Function
  84.  
  85. #End Region
  86.  
  87. #Region " Imports "
  88.  
  89. Imports System.ComponentModel
  90. Imports System.Runtime.InteropServices
  91.  
  92. #End Region
  93.  
  94. Public Class Symbols
  95.  
  96. #Region " P/Invoke "
  97.  
  98. #Region " Methods "
  99.  
  100.    ''' <summary>
  101.    ''' Initializes the symbol handler for a process.
  102.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681351%28v=vs.85%29.aspx
  103.    ''' </summary>
  104.    ''' <param name="hProcess">
  105.    ''' A handle that identifies the caller.
  106.    ''' This value should be unique and nonzero, but need not be a process handle.
  107.    ''' However, if you do use a process handle, be sure to use the correct handle.
  108.    ''' If the application is a debugger, use the process handle for the process being debugged.
  109.    ''' Do not use the handle returned by 'GetCurrentProcess' when debugging another process,
  110.    ''' because calling functions like 'SymLoadModuleEx' can have unexpected results.
  111.    ''' </param>
  112.    ''' <param name="UserSearchPath">
  113.    ''' The path, or series of paths separated by a semicolon (;), that is used to search for symbol files.
  114.    ''' If this parameter is NULL, the library attempts to form a symbol path from the following sources:
  115.    ''' The current working directory of the application.
  116.    ''' The _NT_SYMBOL_PATH environment variable.
  117.    ''' The _NT_ALTERNATE_SYMBOL_PATH environment variable.
  118.    ''' </param>
  119.    ''' <param name="fInvadeProcess">
  120.    ''' If this value is TRUE, enumerates the loaded modules for the process
  121.    ''' and effectively calls the 'SymLoadModule64' function for each module.</param>
  122.    ''' <returns>
  123.    ''' If the function succeeds, the return value is <c>true</c>.
  124.    ''' If the function fails, the return value is <c>false</c>.
  125.    ''' </returns>
  126.    <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  127.    Friend Shared Function SymInitialize(
  128.               ByVal hProcess As IntPtr,
  129.               ByVal UserSearchPath As String,
  130.               <MarshalAs(UnmanagedType.Bool)>
  131.               ByVal fInvadeProcess As Boolean
  132.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  133.    End Function
  134.  
  135.    ''' <summary>
  136.    ''' Deallocates all resources associated with the process handle.
  137.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680696%28v=vs.85%29.aspx
  138.    ''' </summary>
  139.    ''' <param name="hProcess">A handle to the process that was originally passed to the 'SymInitialize' function.</param>
  140.    ''' <returns>
  141.    ''' If the function succeeds, the return value is <c>true</c>.
  142.    ''' If the function fails, the return value is <c>false</c>.
  143.    ''' </returns>
  144.    <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  145.    Friend Shared Function SymCleanup(
  146.               ByVal hProcess As IntPtr
  147.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  148.    End Function
  149.  
  150.    ''' <summary>
  151.    ''' Sets the options mask.
  152.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681366%28v=vs.85%29.aspx
  153.    ''' </summary>
  154.    ''' <param name="SymOptions"></param>
  155.    ''' <returns>The function returns the current options mask.</returns>
  156.    <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  157.    Friend Shared Function SymSetOptions(
  158.               ByVal SymOptions As SymOptionFlags
  159.        ) As Integer
  160.    End Function
  161.  
  162.    ''' <summary>
  163.    ''' Loads the symbol table for the specified module.
  164.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681353%28v=vs.85%29.aspx
  165.    ''' </summary>
  166.    ''' <param name="hProcess">
  167.    ''' A handle to the process that was originally passed to the 'SymInitialize' function.
  168.    ''' </param>
  169.    ''' <param name="hFile">
  170.    ''' The 'h fileA' handle to the file for the executable image.
  171.    ''' This argument is used mostly by debuggers, where the debugger passes the file handle obtained from a debugging event.
  172.    ''' A value of NULL indicates that 'hFile' is not used.
  173.    ''' </param>
  174.    ''' <param name="ImageName">
  175.    ''' The name of the executable image.
  176.    ''' This name can contain a partial path, a full path, or no path at all.
  177.    ''' If the file cannot be located by the name provided, the symbol search path is used.
  178.    ''' </param>
  179.    ''' <param name="ModuleName">
  180.    ''' A shortcut name for the module.
  181.    ''' If the pointer value is NULL, the library creates a name using the base name of the symbol file.
  182.    ''' </param>
  183.    ''' <param name="BaseOfDll">
  184.    ''' The load address of the module.
  185.    ''' If the value is zero, the library obtains the load address from the symbol file.
  186.    ''' The load address contained in the symbol file is not necessarily the actual load address.
  187.    ''' Debuggers and other applications having an actual load address should use the real load address when calling this function.
  188.    ''' If the image is a '.pdb' file, this parameter cannot be zero.
  189.    ''' </param>
  190.    ''' <param name="DllSize">
  191.    ''' The size of the module, in bytes.
  192.    ''' If the value is zero, the library obtains the size from the symbol file.
  193.    ''' The size contained in the symbol file is not necessarily the actual size.
  194.    ''' Debuggers and other applications having an actual size should use the real size when calling this function.
  195.    ''' If the image is a '.pdb' file, this parameter cannot be zero.
  196.    ''' </param>
  197.    ''' <param name="Data">
  198.    ''' A pointer to a 'MODLOAD_DATA' structure that represents headers other than the standard PE header.
  199.    ''' This parameter is optional and can be NULL.
  200.    ''' </param>
  201.    ''' <param name="Flags">
  202.    ''' This parameter can be one or more of the 'SymLoadModuleFlags' Enum values.
  203.    ''' If this parameter is zero, the function loads the modules and the symbols for the module.
  204.    ''' </param>
  205.    ''' <returns>
  206.    ''' If the function succeeds, the return value is the base address of the loaded module.
  207.    ''' If the function fails, the return value is zero. To retrieve extended error information, call 'GetLastError'.
  208.    ''' If the module is already loaded, the return value is zero and 'GetLastError' returns 'ERROR_SUCCESS'.
  209.    ''' </returns>
  210.    <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  211.    Friend Shared Function SymLoadModuleEx(
  212.               ByVal hProcess As IntPtr,
  213.               ByVal hFile As IntPtr,
  214.               ByVal ImageName As String,
  215.               ByVal ModuleName As String,
  216.               ByVal BaseOfDll As Long,
  217.               ByVal DllSize As Integer,
  218.               ByVal Data As IntPtr,
  219.               ByVal Flags As SymLoadModuleFlags
  220.        ) As ULong
  221.    End Function
  222.  
  223.    ''' <summary>
  224.    ''' Enumerates all symbols in a process.
  225.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680718%28v=vs.85%29.aspx
  226.    ''' </summary>
  227.    ''' <param name="hProcess">
  228.    ''' A handle to a process.
  229.    ''' This handle must have been previously passed to the 'SymInitialize' function.
  230.    ''' </param>
  231.    ''' <param name="BaseOfDll">
  232.    ''' The base address of the module.
  233.    ''' If this value is zero and 'Mask' contains an exclamation point (!),
  234.    ''' the function looks across modules.
  235.    ''' If this value is zero and 'Mask' does not contain an exclamation point,
  236.    ''' the function uses the scope established by the 'SymSetContext' function.
  237.    ''' </param>
  238.    ''' <param name="Mask">
  239.    ''' A wildcard string that indicates the names of the symbols to be enumerated.
  240.    ''' The text can optionally contain the wildcards, "*" and "?".
  241.    ''' </param>
  242.    ''' <param name="EnumSymbolsCallback">
  243.    ''' A 'SymEnumSymbolsProc' callback function that receives the symbol information.
  244.    ''' </param>
  245.    ''' <param name="UserContext">
  246.    ''' A user-defined value that is passed to the callback function, or NULL.
  247.    ''' This parameter is typically used by an application to pass a pointer to a data structure
  248.    ''' that provides context for the callback function.
  249.    ''' </param>
  250.    ''' <returns>
  251.    ''' If the function succeeds, the return value is <c>true</c>.
  252.    ''' If the function fails, the return value is <c>false</c>.
  253.    ''' </returns>
  254.    <DllImport("dbghelp.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
  255.    Friend Shared Function SymEnumSymbols(
  256.               ByVal hProcess As IntPtr,
  257.               ByVal BaseOfDll As ULong,
  258.               <MarshalAs(UnmanagedType.LPWStr)>
  259.               ByVal Mask As String,
  260.               ByVal EnumSymbolsCallback As SymEnumSymbolsProc,
  261.               ByVal UserContext As IntPtr
  262.        ) As Boolean
  263.    End Function
  264.  
  265. #End Region
  266.  
  267. #End Region
  268.  
  269. #Region " Types "
  270.  
  271.    ''' <summary>
  272.    ''' Contains symbol information.
  273.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680686%28v=vs.85%29.aspx
  274.    ''' </summary>
  275.    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)>
  276.    Public Class SYMBOL_INFO
  277.  
  278.        ''' <summary>
  279.        ''' The size of the structure, in bytes.
  280.        ''' This member must be set to sizeof(SYMBOL_INFO).
  281.        ''' Note that the total size of the data is the SizeOfStruct + (MaxNameLen - 1) * sizeof(TCHAR).
  282.        ''' The reason to subtract one is that the first character in the name is accounted for in the size of the structure.
  283.        ''' </summary>
  284.        Public SizeOfStruct As UInteger
  285.  
  286.        ''' <summary>
  287.        ''' A unique value that identifies the type data that describes the symbol.
  288.        ''' This value does not persist between sessions.
  289.        ''' </summary>
  290.        Public TypeIndex As UInteger
  291.  
  292.        ''' <summary>
  293.        ''' This member is reserved for system use.
  294.        ''' </summary>
  295.        Public Reserved1 As ULong
  296.  
  297.        ''' <summary>
  298.        ''' This member is reserved for system use.
  299.        ''' </summary>
  300.        Public Reserved2 As ULong
  301.  
  302.        ''' <summary>
  303.        ''' The unique value for the symbol.
  304.        ''' The value associated with a symbol is not guaranteed to be the same each time you run the process.
  305.        ''' For PDB symbols, the index value for a symbol is not generated until
  306.        ''' the symbol is enumerated or retrieved through a search by name or address.
  307.        ''' The index values for all CodeView and COFF symbols are generated when the symbols are loaded.
  308.        ''' </summary>
  309.        Public Index As UInteger
  310.  
  311.        ''' <summary>
  312.        ''' The symbol size, in bytes.
  313.        ''' This value is meaningful only if the module symbols are from a pdb file;
  314.        ''' otherwise, this value is typically zero and should be ignored.
  315.        ''' </summary>
  316.        Public Size As UInteger
  317.  
  318.        ''' <summary>
  319.        ''' The base address of the module that contains the symbol.
  320.        ''' </summary>
  321.        Public ModBase As ULong
  322.  
  323.        ''' <summary>
  324.        ''' The symbol information.
  325.        ''' This member can be one or more of the 'SymFlag' values.
  326.        ''' </summary>
  327.        Public Flags As SymFlag
  328.  
  329.        ''' <summary>
  330.        ''' The value of a constant.
  331.        ''' </summary>
  332.        Public Value As ULong
  333.  
  334.        ''' <summary>
  335.        ''' The virtual address of the start of the symbol.
  336.        ''' </summary>
  337.        Public Address As ULong
  338.  
  339.        ''' <summary>
  340.        ''' The register.
  341.        ''' </summary>
  342.        Public Register As UInteger
  343.  
  344.        ''' <summary>
  345.        ''' The DIA scope.
  346.        ''' For more information, see the Debug Interface Access SDK in the Visual Studio documentation.
  347.        ''' (This resource may not be available in some languages and countries.)
  348.        ''' </summary>
  349.        Public Scope As UInteger
  350.  
  351.        ''' <summary>
  352.        ''' The PDB classification.
  353.        ''' These values are defined in 'Dbghelp.h' in the 'SymTagEnum' enumeration type.
  354.        ''' </summary>
  355.        Public Tag As SymTagEnum
  356.  
  357.        ''' <summary>
  358.        ''' The length of the name, in characters, not including the null-terminating character.
  359.        ''' </summary>
  360.        Public NameLen As UInteger
  361.  
  362.        ''' <summary>
  363.        ''' The size of the Name buffer, in characters.
  364.        ''' If this member is 0, the Name member is not used.
  365.        ''' </summary>
  366.        Public MaxNameLen As UInteger
  367.  
  368.        ''' <summary>
  369.        ''' The name of the symbol.
  370.        ''' The name can be undecorated if the 'SYMOPT_UNDNAME' option is used with the 'SymSetOptions' function.
  371.        ''' </summary>
  372.        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=1024I)>
  373.        Public Name As String
  374.  
  375.    End Class
  376.  
  377. #End Region
  378.  
  379. #Region " Enumerations "
  380.  
  381.    ''' <summary>
  382.    ''' Flags for 'SymLoadModuleEx' function.
  383.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681353%28v=vs.85%29.aspx
  384.    ''' </summary>
  385.    <Description("Enum used as 'Flags' parameter of 'SymLoadModuleEx' function")>
  386.    <FlagsAttribute()>
  387.    Public Enum SymLoadModuleFlags As Integer
  388.  
  389.        ''' <summary>
  390.        ''' Loads the module and the symbols for the module.
  391.        ''' </summary>
  392.        Module_And_Symbols = &H0UI
  393.  
  394.        ''' <summary>
  395.        ''' Loads the module but not the symbols for the module.
  396.        ''' </summary>
  397.        Only_Module = &H4UI
  398.  
  399.        ''' <summary>
  400.        ''' Creates a virtual module named 'ModuleName' at the address specified in 'BaseOfDll'.
  401.        ''' To add symbols to this module, call the 'SymAddSymbol' function.
  402.        ''' </summary>
  403.        Virtual = &H1UI
  404.  
  405.    End Enum
  406.  
  407.    ''' <summary>
  408.    ''' Contains symbol information.
  409.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680686%28v=vs.85%29.aspx
  410.    ''' </summary>
  411.    <Description("Enum used as 'Flags' property of 'SYMBOL_INFO' Class")>
  412.    <FlagsAttribute>
  413.    Public Enum SymFlag As UInteger
  414.  
  415.        ''' <summary>
  416.        ''' The Value member is used.
  417.        ''' </summary>
  418.        VALUEPRESENT = &H1UI
  419.  
  420.        ''' <summary>
  421.        ''' The symbol is a register.
  422.        ''' The Register member is used.
  423.        ''' </summary>
  424.        REGISTER = &H8UI
  425.  
  426.        ''' <summary>
  427.        ''' Offsets are register relative.
  428.        ''' </summary>
  429.        REGREL = &H10UI
  430.  
  431.        ''' <summary>
  432.        ''' Offsets are frame relative.
  433.        ''' </summary>
  434.        FRAMEREL = &H20UI
  435.  
  436.        ''' <summary>
  437.        ''' The symbol is a parameter.
  438.        ''' </summary>
  439.        PARAMETER = &H40UI
  440.  
  441.        ''' <summary>
  442.        ''' The symbol is a local variable.
  443.        ''' </summary>
  444.        LOCAL = &H80UI
  445.  
  446.        ''' <summary>
  447.        ''' The symbol is a constant.
  448.        ''' </summary>
  449.        CONSTANT = &H100UI
  450.  
  451.        ''' <summary>
  452.        ''' The symbol is from the export table.
  453.        ''' </summary>
  454.        EXPORT = &H200UI
  455.  
  456.        ''' <summary>
  457.        ''' The symbol is a forwarder.
  458.        ''' </summary>
  459.        FORWARDER = &H400UI
  460.  
  461.        ''' <summary>
  462.        ''' The symbol is a known function.
  463.        ''' </summary>
  464.        [FUNCTION] = &H800UI
  465.  
  466.        ''' <summary>
  467.        ''' The symbol is a virtual symbol created by the 'SymAddSymbol' function.
  468.        ''' </summary>
  469.        VIRTUAL = &H1000UI
  470.  
  471.        ''' <summary>
  472.        ''' The symbol is a thunk.
  473.        ''' </summary>
  474.        THUNK = &H2000UI
  475.  
  476.        ''' <summary>
  477.        ''' The symbol is an offset into the TLS data area.
  478.        ''' </summary>
  479.        TLSREL = &H4000UI
  480.  
  481.        ''' <summary>
  482.        ''' The symbol is a managed code slot.
  483.        ''' </summary>
  484.        SLOT = &H8000UI
  485.  
  486.        ''' <summary>
  487.        ''' The symbol address is an offset relative to the beginning of the intermediate language block.
  488.        ''' This applies to managed code only.
  489.        ''' </summary>
  490.        ILREL = &H10000UI
  491.  
  492.        ''' <summary>
  493.        ''' The symbol is managed metadata.
  494.        ''' </summary>
  495.        METADATA = &H20000UI
  496.  
  497.        ''' <summary>
  498.        ''' The symbol is a CLR token.
  499.        ''' </summary>
  500.        CLR_TOKEN = &H40000UI
  501.  
  502.    End Enum
  503.  
  504.    ''' <summary>
  505.    ''' Specifies the type of symbol.
  506.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/bkedss5f.aspx
  507.    ''' </summary>
  508.    <Description("Enum used as 'Tag' property of 'SYMBOL_INFO' Class")>
  509.    <Flags>
  510.    Public Enum SymTagEnum As UInteger
  511.  
  512.        ''' <summary>
  513.        ''' Indicates that the symbol has no type.
  514.        ''' </summary>
  515.        Null
  516.  
  517.        ''' <summary>
  518.        ''' Indicates that the symbol is an .exe file.
  519.        ''' There is only one SymTagExe symbol per symbol store.
  520.        ''' It serves as the global scope and does not have a lexical parent.
  521.        ''' </summary>
  522.        Exe
  523.  
  524.        ''' <summary>
  525.        ''' Indicates the compiland symbol for each compiland component of the symbol store.
  526.        ''' For native applications, SymTagCompiland symbols correspond to the object files linked into the image.
  527.        ''' For some kinds of Microsoft Intermediate Language (MSIL) images, there is one compiland per class.
  528.        ''' </summary>
  529.        Compiland
  530.  
  531.        ''' <summary>
  532.        ''' Indicates that the symbol contains extended attributes of the compiland.
  533.        ''' Retrieving these properties may require loading compiland symbols.
  534.        ''' </summary>
  535.        CompilandDetails
  536.  
  537.        ''' <summary>
  538.        ''' Indicates that the symbol is an environment string defined for the compiland.
  539.        ''' </summary>
  540.        CompilandEnv
  541.  
  542.        ''' <summary>
  543.        ''' Indicates that the symbol is a function.
  544.        ''' </summary>
  545.        [Function]
  546.  
  547.        ''' <summary>
  548.        ''' Indicates that the symbol is a nested block.
  549.        ''' </summary>
  550.        Block
  551.  
  552.        ''' <summary>
  553.        ''' Indicates that the symbol is data.
  554.        ''' </summary>
  555.        Data
  556.  
  557.        ''' <summary>
  558.        ''' Indicates that the symbol is for a code annotation.
  559.        ''' Children of this symbol are constant data strings (SymTagData, LocIsConstant, DataIsConstant).
  560.        ''' Most clients ignore this symbol.
  561.        ''' </summary>
  562.        Annotation
  563.  
  564.        ''' <summary>
  565.        ''' Indicates that the symbol is a label.
  566.        ''' </summary>
  567.        Label
  568.  
  569.        ''' <summary>
  570.        ''' Indicates that the symbol is a public symbol. For native applications,
  571.        ''' this symbol is the COFF external symbol encountered while linking the image.
  572.        ''' </summary>
  573.        PublicSymbol
  574.  
  575.        ''' <summary>
  576.        ''' Indicates that the symbol is a user-defined type (structure, class, or union).
  577.        ''' </summary>
  578.        UDT
  579.  
  580.        ''' <summary>
  581.        ''' Indicates that the symbol is an enumeration.
  582.        ''' </summary>
  583.        [Enum]
  584.  
  585.        ''' <summary>
  586.        ''' Indicates that the symbol is a function signature type.
  587.        ''' </summary>
  588.        FunctionType
  589.  
  590.        ''' <summary>
  591.        ''' Indicates that the symbol is a pointer type.
  592.        ''' </summary>
  593.        PointerType
  594.  
  595.        ''' <summary>
  596.        ''' Indicates that the symbol is an array type.
  597.        ''' </summary>
  598.        ArrayType
  599.  
  600.        ''' <summary>
  601.        ''' Indicates that the symbol is a base type.
  602.        ''' </summary>
  603.        BaseType
  604.  
  605.        ''' <summary>
  606.        ''' Indicates that the symbol is a typedef, that is, an alias for another type.
  607.        ''' </summary>
  608.        Typedef
  609.  
  610.        ''' <summary>
  611.        ''' Indicates that the symbol is a base class of a user-defined type.
  612.        ''' </summary>
  613.        BaseClass
  614.  
  615.        ''' <summary>
  616.        ''' Indicates that the symbol is a friend of a user-defined type.
  617.        ''' </summary>
  618.        [Friend]
  619.  
  620.        ''' <summary>
  621.        ''' Indicates that the symbol is a function argument.
  622.        ''' </summary>
  623.        FunctionArgType
  624.  
  625.        ''' <summary>
  626.        ''' Indicates that the symbol is the end location of the function's prologue code.
  627.        ''' </summary>
  628.        FuncDebugStart
  629.  
  630.        ''' <summary>
  631.        ''' Indicates that the symbol is the beginning location of the function's epilogue code.
  632.        ''' </summary>
  633.        FuncDebugEnd
  634.  
  635.        ''' <summary>
  636.        ''' Indicates that the symbol is a namespace name, active in the current scope.
  637.        ''' </summary>
  638.        UsingNamespace
  639.  
  640.        ''' <summary>
  641.        ''' Indicates that the symbol is a virtual table description.
  642.        ''' </summary>
  643.        VTableShape
  644.  
  645.        ''' <summary>
  646.        ''' Indicates that the symbol is a virtual table pointer.
  647.        ''' </summary>
  648.        VTable
  649.  
  650.        ''' <summary>
  651.        ''' Indicates that the symbol is a custom symbol and is not interpreted by DIA.
  652.        ''' </summary>
  653.        Custom
  654.  
  655.        ''' <summary>
  656.        ''' Indicates that the symbol is a thunk used for sharing data between 16 and 32 bit code.
  657.        ''' </summary>
  658.        Thunk
  659.  
  660.        ''' <summary>
  661.        ''' Indicates that the symbol is a custom compiler symbol.
  662.        ''' </summary>
  663.        CustomType
  664.  
  665.        ''' <summary>
  666.        ''' Indicates that the symbol is in metadata.
  667.        ''' </summary>
  668.        ManagedType
  669.  
  670.        ''' <summary>
  671.        ''' Indicates that the symbol is a FORTRAN multi-dimensional array.
  672.        ''' </summary>
  673.        Dimension
  674.  
  675.        ''' <summary>
  676.        ''' Indicates that the symbol represents the call site.
  677.        ''' </summary>
  678.        CallSite
  679.  
  680.        ''' <summary>
  681.        ''' Indicates that the symbol represents the inline site.
  682.        ''' </summary>
  683.        InlineSite
  684.  
  685.        ''' <summary>
  686.        ''' Indicates that the symbol is a base interface.
  687.        ''' </summary>
  688.        BaseInterface
  689.  
  690.        ''' <summary>
  691.        ''' Indicates that the symbol is a vector type.
  692.        ''' </summary>
  693.        VectorType
  694.  
  695.        ''' <summary>
  696.        ''' Indicates that the symbol is a matrix type.
  697.        ''' </summary>
  698.        MatrixType
  699.  
  700.        ''' <summary>
  701.        ''' Indicates that the symbol is a High Level Shader Language type.
  702.        ''' </summary>
  703.        HLSLType
  704.  
  705.    End Enum
  706.  
  707.    ''' <summary>
  708.    ''' Sets the options mask.
  709.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681366%28v=vs.85%29.aspx
  710.    ''' </summary>
  711.    <Description("Enum used as 'SymOptions' parameter of 'SymSetOptions' function")>
  712.    <Flags>
  713.    Public Enum SymOptionFlags As Integer
  714.  
  715.        ''' <summary>
  716.        ''' Enables the use of symbols that do not have an address.
  717.        ''' By default, DbgHelp filters out symbols that do not have an address.
  718.        ''' </summary>
  719.        ALLOW_ZERO_ADDRESS = &H1000000
  720.  
  721.        ''' <summary>
  722.        ''' All symbol searches are insensitive to case.
  723.        ''' </summary>
  724.        CASE_INSENSITIVE = &H1
  725.  
  726.        ''' <summary>
  727.        ''' Pass debug output through OutputDebugString or the SymRegisterCallbackProc64 callback function.
  728.        ''' </summary>
  729.        DEBUG = &H80000000
  730.  
  731.        ''' <summary>
  732.        ''' Symbols are not loaded until a reference is made requiring the symbols be loaded.
  733.        ''' This is the fastest, most efficient way to use the symbol handler.
  734.        ''' </summary>
  735.        DEFERRED_LOADS = &H4
  736.  
  737.        ''' <summary>
  738.        ''' Do not load an unmatched .pdb file.
  739.        ''' Do not load export symbols if all else fails.
  740.        ''' </summary>
  741.        EXACT_SYMBOLS = &H400
  742.  
  743.        ''' <summary>
  744.        ''' Do not display system dialog boxes when there is a media failure such as no media in a drive.
  745.        ''' Instead, the failure happens silently.
  746.        ''' </summary>
  747.        FAIL_CRITICAL_ERRORS = &H200
  748.  
  749.        ''' <summary>
  750.        ''' If there is both an uncompressed and a compressed file available, favor the compressed file.
  751.        ''' This option is good for slow connections.
  752.        ''' </summary>
  753.        FAVOR_COMPRESSED = &H800000
  754.  
  755.        ''' <summary>
  756.        ''' Ignore path information in the CodeView record of the image header when loading a .pdb file.
  757.        ''' </summary>
  758.        IGNORE_CVREC = &H80
  759.  
  760.        ''' <summary>
  761.        ''' When debugging on 64-bit Windows, include any 32-bit modules.
  762.        ''' </summary>
  763.        INCLUDE_32BIT_MODULES = &H2000
  764.  
  765.        ''' <summary>
  766.        ''' Disable checks to ensure a file (.exe, .dbg., or .pdb) is the correct file.
  767.        ''' Instead, load the first file located.
  768.        ''' </summary>
  769.        LOAD_ANYTHING = &H40
  770.  
  771.        ''' <summary>
  772.        ''' Loads line number information.
  773.        ''' </summary>
  774.        LOAD_LINES = &H10
  775.  
  776.        ''' <summary>
  777.        ''' All C++ decorated symbols containing the symbol separator "::" are replaced by "__".
  778.        ''' This option exists for debuggers that cannot handle parsing real C++ symbol names.
  779.        ''' </summary>
  780.        NO_CPP = &H8
  781.  
  782.        ''' <summary>
  783.        ''' Prevents prompting for validation from the symbol server.
  784.        ''' </summary>
  785.        NO_PROMPTS = &H80000
  786.  
  787.        ''' <summary>
  788.        ''' Prevents symbols from being loaded when the caller examines symbols across multiple modules.
  789.        ''' Examine only the module whose symbols have already been loaded.
  790.        ''' </summary>
  791.        NO_UNQUALIFIED_LOADS = &H100
  792.  
  793.        ''' <summary>
  794.        ''' DbgHelp will not load any symbol server other than SymSrv. SymSrv will not use the downstream store specified in _NT_SYMBOL_PATH. After this flag has been set, it cannot be cleared.
  795.        ''' DbgHelp 6.0 and 6.1:  This flag can be cleared.
  796.        ''' DbgHelp 5.1:  This value is not supported.
  797.        ''' </summary>
  798.        SECURE = &H40000
  799.  
  800.        ''' <summary>
  801.        ''' All symbols are presented in undecorated form.
  802.        ''' This option has no effect on global or local symbols because they are stored undecorated.
  803.        ''' This option applies only to public symbols.
  804.        ''' </summary>
  805.        UNDNAME = &H2
  806.  
  807.    End Enum
  808.  
  809. #End Region
  810.  
  811. #Region " Delegates "
  812.  
  813.    ''' <summary>
  814.    ''' An application-defined callback function used with the 'SymEnumSymbols', 'SymEnumTypes', and 'SymEnumTypesByName' functions.
  815.    ''' </summary>
  816.    ''' <param name="pSymInfo">
  817.    ''' A pointer to a 'SYMBOL_INFO' structure that provides information about the symbol.
  818.    ''' </param>
  819.    ''' <param name="SymbolSize">
  820.    ''' The size of the symbol, in bytes.
  821.    ''' The size is calculated and is actually a guess.
  822.    ''' In some cases, this value can be zero.
  823.    ''' </param>
  824.    ''' <param name="UserContext">
  825.    ''' The user-defined value passed from the 'SymEnumSymbols' or 'SymEnumTypes' function, or NULL.
  826.    ''' This parameter is typically used by an application to pass a pointer to a data structure
  827.    ''' that provides context information for the callback function.</param>
  828.    ''' <returns>
  829.    ''' If the function returns <c>true</c>, the enumeration will continue.
  830.    ''' If the function returns <c>false</c>, the enumeration will stop.
  831.    ''' </returns>
  832.    Friend Delegate Function SymEnumSymbolsProc(
  833.           ByVal pSymInfo As IntPtr,
  834.           ByVal SymbolSize As UInteger,
  835.           ByVal UserContext As IntPtr
  836.    ) As Boolean
  837.  
  838. #End Region
  839.  
  840. End Class


En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #401 en: 3 Agosto 2014, 09:05 am »

Como convertir una expresión de un valor Hexadecimal al tipo de expresión que se usa en VB.NET:

Nota: Esta es una forma más eficiente que la que posteé hace mucho tiempo.

Código
  1.   ' Hex To VBHex
  2.    ' By Elektro
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    ' MsgBox(HexToVBHex("FF4"))                        ' Result: &HFF4
  7.    ' MsgBox(HexToVBHex("0xFF4"))                      ' Result: &HFF4
  8.    ' Dim Value As Integer = CInt(HexToVBHex("0xFF4")) ' Result: 4084
  9.    '
  10.    ''' <summary>
  11.    ''' Converts an Hexadecimal value to VisualBasic Hexadecimal syntax.
  12.    ''' </summary>
  13.    ''' <param name="Value">The Hexadecimal value as String.</param>
  14.    ''' <returns>System.String.</returns>
  15.    Public Function HexToVBHex(ByVal Value As String) As String
  16.  
  17.        If (String.IsNullOrEmpty(Value) Or String.IsNullOrWhiteSpace(Value)) Then
  18.            Throw New ArgumentNullException(Value)
  19.        End If
  20.  
  21.        Return String.Format("&H{0}", Value.
  22.                                      TrimStart({"0"c, "x"c, "X"c, " "c, ControlChars.NullChar}).
  23.                                      TrimEnd({" "c, ControlChars.NullChar}))
  24.  
  25.    End Function



Como obtener una cadena de texto aleatoria ...dado un set de caracteres, con la posibilidad de randomizar también el String-Case (upper-case/lower-case) de cada letra.

Código
  1.    Dim Randomizer As New Random
  2.  
  3.    ' Get Random String
  4.    ' // By Elektro
  5.    '
  6.    ' Usage Examples :
  7.    ' MsgBox(GetRandomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 10))
  8.    ' MsgBox(GetRandomString("abcdefghijklmnopqrstuvwxyz", 10, RandomizeCase:=True))
  9.    '
  10.    ''' <summary>
  11.    ''' Gets a random string.
  12.    ''' </summary>
  13.    ''' <param name="CharacterSet">Indicates the characters to randomize.</param>
  14.    ''' <param name="StringLength">Indicates the resulting string length.</param>
  15.    ''' <param name="RandomizeCase">If set to <c>true</c>, lower-case and upper-case are randomized.</param>
  16.    ''' <returns>System.String.</returns>
  17.    ''' <exception cref="System.Exception">
  18.    ''' CharacterSet is empty.
  19.    ''' or
  20.    ''' String-Length must be greater than 0.
  21.    ''' </exception>
  22.    Private Function GetRandomString(ByVal CharacterSet As Char(),
  23.                                     ByVal StringLength As Integer,
  24.                                     Optional ByVal RandomizeCase As Boolean = False) As String
  25.  
  26.        Select Case CharacterSet.Count
  27.  
  28.            Case Is = 0
  29.                Throw New Exception("CharacterSet is empty.")
  30.  
  31.            Case Is = 1
  32.                Return New String(CharacterSet.First, Math.Abs(StringLength))
  33.  
  34.            Case Else
  35.  
  36.                Select Case StringLength
  37.  
  38.                    Case Is < 1
  39.                        Throw New Exception("String-Length must be greater than 0.")
  40.  
  41.                    Case Else
  42.  
  43.                        Dim CharSetLength As Integer = CharacterSet.Length
  44.                        Dim CharSB As New System.Text.StringBuilder
  45.  
  46.                        Do Until CharSB.Length = StringLength
  47.  
  48.                            If Not RandomizeCase Then
  49.                                CharSB.Append(CharacterSet(Randomizer.Next(0, CharSetLength)))
  50.  
  51.                            Else
  52.  
  53.                                Select Case Randomizer.Next(0, 2)
  54.  
  55.                                    Case 0 ' Lower-Case
  56.                                        CharSB.Append(Char.ToLower(CharacterSet(Randomizer.Next(0, CharSetLength))))
  57.  
  58.                                    Case 1 ' Upper-Case
  59.                                        CharSB.Append(Char.ToUpper(CharacterSet(Randomizer.Next(0, CharSetLength))))
  60.  
  61.                                End Select
  62.  
  63.                            End If '/ Not RandomizeCase
  64.  
  65.                        Loop '/ CharSB.Length = StringLength
  66.  
  67.                        Return CharSB.ToString
  68.  
  69.                End Select '/ StringLength
  70.  
  71.        End Select '/  CharacterSet.Count
  72.  
  73.    End Function




Una expresión regular para obtener las Ipv4 de un String:

Código
  1.    ' RegEx-Match IPv4
  2.    ' By Elektro
  3.    '
  4.    ' expression taken from: http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
  5.    '
  6.    ' Usage Examples :
  7.    ' Dim Addresses As String = "127.0.0.1 | 192.17.200.13 | 255.255.255.255 | 999.999.999.999"
  8.    ' Dim Matches As System.Text.RegularExpressions.MatchCollection = RegExMatch_IPv4(Addresses)
  9.    ' For Each m As System.Text.RegularExpressions.Match In Matches
  10.    '     MessageBox.Show(m.Value)
  11.    ' Next
  12.    '
  13.    ''' <summary>
  14.    ''' Matches the IPv4 addresses contained in a String, using Regular Expressions.
  15.    ''' </summary>
  16.    ''' <param name="str">The string.</param>
  17.    ''' <param name="options">The RegEx options.</param>
  18.    ''' <returns>System.Text.RegularExpressions.MatchCollection.</returns>
  19.    Private Function RegExMatch_IPv4(ByVal str As String,
  20.                                     Optional ByVal options As System.Text.RegularExpressions.RegexOptions =
  21.                                                               System.Text.RegularExpressions.RegexOptions.None
  22.                                                               ) As System.Text.RegularExpressions.MatchCollection
  23.  
  24.        ' Match criteria:
  25.        '
  26.        ' ([0-255].[0-255].[0-255].[0-255])
  27.  
  28.        Dim Pattern As String =
  29.            <a><![CDATA[((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])]]></a>.Value
  30.  
  31.        Return New System.Text.RegularExpressions.Regex(Pattern).Matches(str)
  32.  
  33.    End Function



Una expresión regular para obtener las Ipv6 de un String:

Nota: La expresión da fallos con ip's comprimidas como por ejemplo esta:
Código:
fec0:fff::1
por lo demás todo bien.

Código
  1.    ' RegEx-Match IPv6
  2.    ' By Elektro
  3.    '
  4.    ' expression taken from: http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
  5.    '
  6.    ' Usage Examples :
  7.    ' Dim Addresses As String = "FE80:0000:0000:0000:0202:B3FF:FE1E:8329 | FEC0:FFFF:0000:0000:0000:0000:0000:1"
  8.    ' Dim Matches As System.Text.RegularExpressions.MatchCollection = RegExMatch_IPv6(Addresses)
  9.    ' For Each m As System.Text.RegularExpressions.Match In Matches
  10.    '     MessageBox.Show(m.Value)
  11.    ' Next
  12.    '
  13.    ''' <summary>
  14.    ''' Matches the IPv6 addresses (full or compressed) contained in a String, using Regular Expressions.
  15.    ''' </summary>
  16.    ''' <param name="str">The string.</param>
  17.    ''' <param name="options">The RegEx options.</param>
  18.    ''' <returns>System.Text.RegularExpressions.MatchCollection.</returns>
  19.    Private Function RegExMatch_IPv6(ByVal str As String,
  20.                                     Optional ByVal options As System.Text.RegularExpressions.RegexOptions =
  21.                                                               System.Text.RegularExpressions.RegexOptions.None
  22.                                                               ) As System.Text.RegularExpressions.MatchCollection
  23.  
  24.        Dim Pattern As String =
  25.            <a><![CDATA[(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))]]></a>.Value
  26.  
  27.        Return New System.Text.RegularExpressions.Regex(Pattern).Matches(str)
  28.  
  29.    End Function


« Última modificación: 3 Agosto 2014, 10:07 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #402 en: 3 Agosto 2014, 10:40 am »

Ejemplo de como usar un Proxy:

Código
  1.        Dim Request As Net.HttpWebRequest = Net.HttpWebRequest.Create("http://whatismyipaddress.com/")
  2.  
  3.        With Request
  4.            .Proxy = New Net.WebProxy(Host:="93.115.8.229", Port:=7808)
  5.        End With
  6.  
  7.        Using StrReader As New IO.StreamReader(Request.GetResponse().GetResponseStream)
  8.  
  9.            Dim IPRegEx As New System.Text.RegularExpressions.Regex("(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")
  10.            Dim IPValue As String = IPRegEx.Match(StrReader.ReadToEnd).Value
  11.  
  12.            MessageBox.Show(String.Format("Your IP Adress is: {0}", IPValue))
  13.  
  14.        End Using



Hace parpadear la ventana o el botón de la barra de tareas de un proceso

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 08-03-2014
  4. ' ***********************************************************************
  5. ' <copyright file="WindowFlasher.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. ''Flash the Button TaskBar until the window becomes active.
  13. 'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.TaskBar Or WindowFlasher.FlashFlags.Until_Foreground)
  14.  
  15. ''Flash the Caption and the Button TaskBar until the "Stop" flag is set.
  16. 'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.All Or WindowFlasher.FlashFlags.Until_Stop)
  17.  
  18. ''Set the "Stop" flag, to stop flashing.
  19. 'WindowFlasher.Flash(Me.Handle, WindowFlasher.FlashFlags.Stop)
  20.  
  21. #End Region
  22.  
  23. #Region " Imports "
  24.  
  25. Imports System.ComponentModel
  26. Imports System.Runtime.InteropServices
  27.  
  28. #End Region
  29.  
  30. ''' <summary>
  31. ''' Flashes a Window and/or it's button in the TaskBar.
  32. ''' </summary>
  33. Public Class WindowFlasher
  34.  
  35. #Region " P/Invoke "
  36.  
  37.    ''' <summary>
  38.    ''' Contains Native Windows API Methods.
  39.    ''' </summary>
  40.    Friend Class NativeMethods
  41.  
  42. #Region " Methods "
  43.  
  44.        ''' <summary>
  45.        ''' Flashes the specified window.
  46.        ''' It does not change the active state of the window.
  47.        ''' For more info see here:
  48.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms679347%28v=vs.85%29.aspx
  49.        ''' </summary>
  50.        ''' <param name="pwfi">A pointer to a FLASHWINFO structure.</param>
  51.        ''' <returns>
  52.        ''' The return value specifies the window's state before the call to the FlashWindowEx function.
  53.        ''' If the window caption was drawn as active before the call, the return value is nonzero.
  54.        ''' Otherwise, the return value is zero.
  55.        ''' </returns>
  56.        <DllImport("user32.dll")>
  57.        Friend Shared Function FlashWindowEx(
  58.               ByRef pwfi As FLASHWINFO
  59.        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  60.        End Function
  61.  
  62. #End Region
  63.  
  64. #Region " Structures "
  65.  
  66.        ''' <summary>
  67.        ''' Contains the flash status for a window and the number of times the system should flash the window.
  68.        ''' For more info see here:
  69.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms679348%28v=vs.85%29.aspx
  70.        ''' </summary>
  71.        <StructLayout(LayoutKind.Sequential)>
  72.        Friend Structure FLASHWINFO
  73.  
  74.            ''' <summary>
  75.            ''' The size of the structure, in bytes.
  76.            ''' </summary>
  77.            Friend cbSize As UInteger
  78.  
  79.            ''' <summary>
  80.            ''' A handle to the window to be flashed.
  81.            ''' The window can be either opened or minimized.
  82.            ''' </summary>
  83.            Friend hwnd As IntPtr
  84.  
  85.            ''' <summary>
  86.            ''' The flash status.
  87.            ''' </summary>
  88.            Friend dwFlags As FlashFlags
  89.  
  90.            ''' <summary>
  91.            ''' The number of times to flash the window.
  92.            ''' </summary>
  93.            Friend uCount As UInteger
  94.  
  95.            ''' <summary>
  96.            ''' The rate at which the window is to be flashed, in milliseconds.
  97.            ''' If dwTimeout is zero, the function uses the default cursor blink rate.
  98.            ''' </summary>
  99.            Friend dwTimeout As UInteger
  100.  
  101.        End Structure
  102.  
  103. #End Region
  104.  
  105.    End Class
  106.  
  107. #End Region
  108.  
  109. #Region " Enumerations "
  110.  
  111.    ''' <summary>
  112.    ''' Contains the flash status for a window.
  113.    ''' </summary>
  114.    <Description("Enum used as 'FlashFlags' parameter in 'FlashWindow' function.")>
  115.    <Flags>
  116.    Public Enum FlashFlags As Integer
  117.  
  118.        ''' <summary>
  119.        ''' Stop flashing.
  120.        ''' The system restores the window to its original state.
  121.        ''' </summary>    
  122.        [Stop] = 0I
  123.  
  124.        ''' <summary>
  125.        ''' Flash the window caption.
  126.        ''' </summary>
  127.        Caption = 1I
  128.  
  129.        ''' <summary>
  130.        ''' Flash the taskbar button.
  131.        ''' </summary>
  132.        TaskBar = 2I
  133.  
  134.        ''' <summary>
  135.        ''' Flash both the window caption and taskbar button.
  136.        ''' This is equivalent to setting the 'Caption Or TaskBar' flags.
  137.        ''' </summary>
  138.        All = 3I
  139.  
  140.        ''' <summary>
  141.        ''' Flash continuously, until the 'Stop' flag is set.
  142.        ''' </summary>
  143.        Until_Stop = 4I
  144.  
  145.        ''' <summary>
  146.        ''' Flash continuously until the window comes to the foreground.
  147.        ''' </summary>
  148.        Until_Foreground = 12I
  149.  
  150.    End Enum
  151.  
  152. #End Region
  153.  
  154. #Region " Public Methods "
  155.  
  156.    ''' <summary>
  157.    ''' Flashes the specified window.
  158.    ''' It does not change the active state of the window.
  159.    ''' </summary>
  160.    ''' <param name="Handle">
  161.    ''' Indicates the handle to the window to flash.
  162.    ''' </param>
  163.    ''' <param name="FlashFlags">
  164.    ''' Indicates the flash flags.
  165.    ''' </param>
  166.    ''' <param name="FlashCount">
  167.    ''' Indicates the number of times to flash the window.
  168.    ''' </param>
  169.    ''' <param name="FlashDelay">
  170.    ''' Indicates the rate at which the window is to be flashed, in milliseconds.
  171.    ''' If dwTimeout is zero, the function uses the default cursor blink rate.
  172.    ''' </param>
  173.    ''' <returns>
  174.    ''' The return value specifies the window's state before the call to the FlashWindowEx function.
  175.    ''' If the window caption was drawn as active before the call, the return value is nonzero.
  176.    ''' Otherwise, the return value is zero.
  177.    ''' </returns>
  178.    Public Shared Function Flash(ByVal [Handle] As IntPtr,
  179.                                 ByVal FlashFlags As FlashFlags,
  180.                                 Optional ByVal FlashCount As UInteger = UInteger.MaxValue,
  181.                                 Optional ByVal FlashDelay As UInteger = 0UI) As Boolean
  182.  
  183.        Dim fInfo As New NativeMethods.FLASHWINFO()
  184.  
  185.        With fInfo
  186.  
  187.            .cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo))
  188.            .hwnd = [Handle]
  189.            .dwFlags = FlashFlags
  190.            .uCount = FlashCount
  191.            .dwTimeout = FlashDelay
  192.  
  193.        End With
  194.  
  195.        Return NativeMethods.FlashWindowEx(fInfo)
  196.  
  197.    End Function
  198.  
  199. #End Region
  200.  
  201. End Class
  202.  
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #403 en: 3 Agosto 2014, 17:23 pm »

Ejemplos de uso de la librería dnlib (de4dot): https://github.com/0xd4d/dnlib

Aunque de momento es una Class muy básica, pues dnlib es muy extenso pero con documentación muy escasa.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 08-03-2014
  4. ' ***********************************************************************
  5. ' <copyright file="dnlibHelper.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Private Sub Test() Handles MyBase.Shown
  13. '
  14. '    Dim Assembly As ModuleDefMD =
  15. '        dnlibHelper.LoadAssembly("C:\Application.exe")
  16. '
  17. '    Dim FrameworkVersion As String =
  18. '        dnlibHelper.GetRuntimeVersion(Assembly)
  19. '
  20. '    Dim IsNativeCoded As Boolean =
  21. '        dnlibHelper.AssemblyHasNativeCode(Assembly)
  22. '
  23. '    Dim Methods As List(Of MethodDef) =
  24. '        dnlibHelper.GetMethods(Assembly, "Main") ' Searchs a Class named "Main"
  25. '
  26. '    For Each Method As MethodDef In Methods
  27. '
  28. '        ' If method contains instructions then...
  29. '        If Method.HasBody Then
  30. '
  31. '            Dim sb As New System.Text.StringBuilder
  32. '            With sb
  33. '                .AppendLine(String.Format("Method Name: {0}", Method.Name))
  34. '                .AppendLine()
  35. '                .AppendLine(String.Format("Method Signature: {0}", Method.Signature.ToString))
  36. '                .AppendLine()
  37. '                .AppendLine(String.Format("Method Instructions: {0}", Environment.NewLine &
  38. '                                          String.Join(Environment.NewLine, Method.Body.Instructions)))
  39. '            End With
  40. '
  41. '            MessageBox.Show(sb.ToString)
  42. '
  43. '        End If ' method.HasBody
  44. '
  45. '    Next Method
  46. '
  47. 'End Sub
  48.  
  49. #End Region
  50.  
  51. #Region " Imports "
  52.  
  53. Imports dnlib.DotNet
  54. Imports dnlib.DotNet.Emit
  55.  
  56. #End Region
  57.  
  58. ''' <summary>
  59. ''' Class dnlibHelper. This class cannot be inherited.
  60. ''' </summary>
  61. Public NotInheritable Class dnlibHelper
  62.  
  63.    ''' <summary>
  64.    ''' Loads an Assembly into a ModuleDefMD instance.
  65.    ''' </summary>
  66.    ''' <param name="Assembly">The assembly filepath.</param>
  67.    ''' <returns>ModuleDefMD.</returns>
  68.    Public Shared Function LoadAssembly(ByVal Assembly As String) As ModuleDefMD
  69.  
  70.        Return ModuleDefMD.Load(Assembly)
  71.  
  72.    End Function
  73.  
  74.    ''' <summary>
  75.    ''' Determines whether a .Net Assembly has native code (C++/CLI).
  76.    ''' </summary>
  77.    ''' <param name="Assembly">The Assembly.</param>
  78.    ''' <returns><c>true</c> if Assembly contains native code; otherwise, <c>false</c>.</returns>
  79.    Public Shared Function AssemblyHasNativeCode(ByVal Assembly As ModuleDef) As Boolean
  80.  
  81.        If Assembly.IsILOnly Then
  82.            ' This assembly has only IL code, and no native code (for example it's a C# or VB.NET assembly)
  83.            Return True
  84.  
  85.        Else
  86.            ' This assembly has native code (for example it's C++/CLI)
  87.            Return False
  88.  
  89.        End If
  90.  
  91.    End Function
  92.  
  93.    ''' <summary>
  94.    ''' Determines whether a .Net Assembly has native code (C++/CLI).
  95.    ''' </summary>
  96.    ''' <param name="Assembly">The Assembly filepath.</param>
  97.    ''' <returns><c>true</c> if Assembly contains native code; otherwise, <c>false</c>.</returns>
  98.    Public Shared Function AssemblyHasNativeCode(ByVal Assembly As String) As Boolean
  99.  
  100.        Using ass As ModuleDefMD = ModuleDefMD.Load(Assembly)
  101.  
  102.            Return AssemblyHasNativeCode(ass)
  103.  
  104.        End Using
  105.  
  106.    End Function
  107.  
  108.    ''' <summary>
  109.    ''' Gets the .Net Framework runtime version of a .Net assembly.
  110.    ''' </summary>
  111.    ''' <param name="Assembly">The assembly.</param>
  112.    ''' <returns>System.String.</returns>
  113.    Public Shared Function GetRuntimeVersion(ByVal Assembly As ModuleDefMD) As String
  114.  
  115.        Return Assembly.RuntimeVersion
  116.  
  117.    End Function
  118.  
  119.    ''' <summary>
  120.    ''' Gets the .Net Framework runtime version of a .Net assembly.
  121.    ''' </summary>
  122.    ''' <param name="Assembly">The assembly filepath.</param>
  123.    ''' <returns>System.String.</returns>
  124.    Public Shared Function GetRuntimeVersion(ByVal Assembly As String) As String
  125.  
  126.        Using ass As ModuleDefMD = ModuleDefMD.Load(Assembly)
  127.            Return GetRuntimeVersion(ass)
  128.        End Using
  129.  
  130.    End Function
  131.  
  132.    ''' <summary>
  133.    ''' Gets all the Types defined (including nested Types) inside a .Net assembly.
  134.    ''' </summary>
  135.    ''' <param name="Assembly">The assembly.</param>
  136.    ''' <returns>TypeDef().</returns>
  137.    Public Shared Function GetTypes(ByVal Assembly As ModuleDefMD) As List(Of TypeDef)
  138.  
  139.        Return Assembly.GetTypes.ToList
  140.  
  141.    End Function
  142.  
  143.    ''' <summary>
  144.    ''' Gets all the Methods defined in a existing Type inside a .Net assembly.
  145.    ''' </summary>
  146.    ''' <param name="Assembly">The assembly.</param>
  147.    ''' <param name="TypeName">Name of the type to find.</param>
  148.    ''' <returns>MethodDef().</returns>
  149.    Public Shared Function GetMethods(ByVal Assembly As ModuleDefMD,
  150.                                      ByVal TypeName As String) As List(Of MethodDef)
  151.  
  152.        Dim methods As List(Of MethodDef) = Nothing
  153.  
  154.        For Each t As TypeDef In Assembly.GetTypes
  155.  
  156.            If t.HasMethods AndAlso t.Name.String.Equals(TypeName, StringComparison.OrdinalIgnoreCase) Then
  157.                methods = t.Methods.ToList
  158.                Exit For
  159.            End If
  160.  
  161.        Next t
  162.  
  163.        Return methods
  164.  
  165.    End Function
  166.  
  167. End Class
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #404 en: 3 Agosto 2014, 17:55 pm »

Ya van 30 páginas xD

Pues vamos a por las 300 :)

(triplicando mis espectativas xD)

Saludos!
En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #405 en: 4 Agosto 2014, 18:44 pm »

Una Class para ayudar a implementar una lista MRU (MostRecentUsed)

( La parte gráfica sobre como implementar los items en un menú no la voy a explicar, al menos en esta publicación )





Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 08-04-2014
  4. ' ***********************************************************************
  5. ' <copyright file="MRU.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Public Class Form1
  13. '
  14. '    ' Initialize a new List of MostRecentUsed-Item
  15. '    Dim MRUList As New List(Of MRU.Item)
  16. '
  17. '    Private Sub Test() Handles MyBase.Shown
  18. '
  19. '        ' Add some items into the collection.
  20. '        With MRUList
  21. '            .Add(New MRU.Item("C:\File1.ext"))
  22. '            .Add(New MRU.Item("C:\File2.ext") With {.Date = Date.Today,
  23. '                                                    .Icon = Bitmap.FromFile("C:\Image.ico"),
  24. '                                                    .Tag = Nothing})
  25. '        End With
  26. '
  27. '        ' Save the MRUItem collection to local file.
  28. '        MRU.IO.Save(MRUList, ".\MRU.tmp")
  29. '
  30. '        ' Load the saved collection from local file.
  31. '        For Each MRUItem As MRU.Item In MRU.IO.Load(Of List(Of MRU.Item))(".\MRU.tmp")
  32. '            MessageBox.Show(MRUItem.FilePath)
  33. '        Next MRUItem
  34. '
  35. '        ' Just another way to load the collection:
  36. '        MRU.IO.Load(MRUList, ".\MRU.tmp")
  37. '
  38. '    End Sub
  39. '
  40. 'End Class
  41.  
  42. #End Region
  43.  
  44. #Region " MostRecentUsed "
  45.  
  46. ''' <summary>
  47. ''' Class MRU (MostRecentUsed).
  48. ''' Administrates the usage of a MRU item collection.
  49. ''' </summary>
  50. Public Class MRU
  51.  
  52. #Region " Constructors "
  53.  
  54.    ''' <summary>
  55.    ''' Prevents a default instance of the <see cref="MRU"/> class from being created.
  56.    ''' </summary>
  57.    Private Sub New()
  58.    End Sub
  59.  
  60. #End Region
  61.  
  62. #Region " Types "
  63.  
  64. #Region "IO"
  65.  
  66.    ''' <summary>
  67.    ''' Performs IO operations with a <see cref="MRU.Item"/> Collection.
  68.    ''' </summary>
  69.    Public Class [IO]
  70.  
  71. #Region " Constructors "
  72.  
  73.        ''' <summary>
  74.        ''' Prevents a default instance of the <see cref="MRU.IO"/> class from being created.
  75.        ''' </summary>
  76.        Private Sub New()
  77.        End Sub
  78.  
  79. #End Region
  80.  
  81. #Region " Public Methods "
  82.  
  83.        ''' <summary>
  84.        ''' Saves the specified MRU List to local file, using binary serialization.
  85.        ''' </summary>
  86.        ''' <typeparam name="T"></typeparam>
  87.        ''' <param name="MRUItemCollection">The <see cref="MRU.Item"/> Collection.</param>
  88.        ''' <param name="filepath">The filepath to save the <see cref="MRU.Item"/> Collection.</param>
  89.        Public Shared Sub Save(Of T)(ByVal MRUItemCollection As T,
  90.                                     ByVal filepath As String)
  91.  
  92.            Dim Serializer = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
  93.  
  94.            ' Serialization.
  95.            Using Writer As New System.IO.FileStream(filepath, System.IO.FileMode.Create)
  96.                Serializer.Serialize(Writer, MRUItemCollection)
  97.            End Using ' Writer
  98.  
  99.        End Sub
  100.  
  101.        ''' <summary>
  102.        ''' Loads the specified <see cref="MRU.Item"/> Collection from a local file, using binary deserialization.
  103.        ''' </summary>
  104.        ''' <typeparam name="T"></typeparam>
  105.        ''' <param name="MRUItemCollection">The ByRefered <see cref="MRU.Item"/> collection.</param>
  106.        ''' <param name="filepath">The filepath to load its <see cref="MRU.Item"/> Collection.</param>
  107.        Public Shared Sub Load(Of T)(ByRef MRUItemCollection As T,
  108.                                     ByVal filepath As String)
  109.  
  110.            Dim Serializer = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
  111.  
  112.            ' Deserialization.
  113.            Using Reader As New System.IO.FileStream(filepath, System.IO.FileMode.Open)
  114.  
  115.                MRUItemCollection = Serializer.Deserialize(Reader)
  116.  
  117.            End Using ' Reader
  118.  
  119.        End Sub
  120.  
  121.        ''' <summary>
  122.        ''' Loads the specified <see cref="MRU.Item"/> Collection from a local file, using the specified deserialization.
  123.        ''' </summary>
  124.        ''' <typeparam name="T"></typeparam>
  125.        ''' <param name="filepath">The filepath to load its <see cref="MRU.Item"/> Collection.</param>
  126.        Public Shared Function Load(Of T)(ByVal filepath As String) As T
  127.  
  128.            Dim Serializer = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
  129.  
  130.            ' Deserialization.
  131.            Using Reader As New System.IO.FileStream(filepath, System.IO.FileMode.Open)
  132.  
  133.                Return Serializer.Deserialize(Reader)
  134.  
  135.            End Using ' Reader
  136.  
  137.        End Function
  138.  
  139. #End Region
  140.  
  141.    End Class
  142.  
  143. #End Region
  144.  
  145. #Region " Item "
  146.  
  147.    ''' <summary>
  148.    ''' An Item for a MostRecentUsed-Item collection that stores the item filepath and optionally additional info.
  149.    ''' This Class can be serialized.
  150.    ''' </summary>
  151.    <Serializable()>
  152.    Public Class Item
  153.  
  154. #Region " Constructors "
  155.  
  156.        ''' <summary>
  157.        ''' Prevents a default instance of the <see cref="MRU.Item"/> class from being created.
  158.        ''' </summary>
  159.        Private Sub New()
  160.        End Sub
  161.  
  162.        ''' <summary>
  163.        ''' Initializes a new instance of the <see cref="MRU.Item"/> class.
  164.        ''' </summary>
  165.        ''' <param name="FilePath">The item filepath.</param>
  166.        ''' <exception cref="System.ArgumentNullException">FilePath</exception>
  167.        Public Sub New(ByVal FilePath As String)
  168.  
  169.            If FilePath Is Nothing Then
  170.                Throw New ArgumentNullException("FilePath")
  171.            End If
  172.  
  173.            Me._FilePath = FilePath
  174.  
  175.        End Sub
  176.  
  177.        ''' <summary>
  178.        ''' Initializes a new instance of the <see cref="MRU.Item"/> class.
  179.        ''' </summary>
  180.        ''' <param name="File">The fileinfo object.</param>
  181.        Public Sub New(ByVal File As System.IO.FileInfo)
  182.  
  183.            Me.New(File.FullName)
  184.  
  185.        End Sub
  186.  
  187. #End Region
  188.  
  189. #Region " Properties "
  190.  
  191.        ''' <summary>
  192.        ''' Gets the item filepath.
  193.        ''' </summary>
  194.        ''' <value>The file path.</value>
  195.        Public ReadOnly Property FilePath As String
  196.            Get
  197.                Return Me._FilePath
  198.            End Get
  199.        End Property
  200.        Private _FilePath As String = String.Empty
  201.  
  202.        ''' <summary>
  203.        ''' Gets the FileInfo object of the item.
  204.        ''' </summary>
  205.        ''' <value>The FileInfo object.</value>
  206.        Public ReadOnly Property FileInfo As System.IO.FileInfo
  207.            Get
  208.                Return New System.IO.FileInfo(FilePath)
  209.            End Get
  210.        End Property
  211.  
  212.        ''' <summary>
  213.        ''' (Optionally) Gets or sets the item last-time open date.
  214.        ''' </summary>
  215.        ''' <value>The index.</value>
  216.        Public Property [Date] As Date
  217.  
  218.        ''' <summary>
  219.        ''' (Optionally) Gets or sets the item icon.
  220.        ''' </summary>
  221.        ''' <value>The icon.</value>
  222.        Public Property Icon As Bitmap
  223.  
  224.        ''' <summary>
  225.        ''' (Optionally) Gets or sets the item tag.
  226.        ''' </summary>
  227.        ''' <value>The tag object.</value>
  228.        Public Property Tag As Object
  229.  
  230. #End Region
  231.  
  232.    End Class
  233.  
  234. #End Region
  235.  
  236. #End Region
  237.  
  238. End Class
  239.  
  240. #End Region
« Última modificación: 4 Agosto 2014, 18:58 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #406 en: 4 Agosto 2014, 20:13 pm »

Ejemplos de uso de la librería nDDE para controlar un navegador compatible (aunque la verdad, DDE es muy limitado ...por no decir obsoleto, es preferible echar mano de UI Automation).

Nota: Aquí teneis algunos ServiceNames y Topics de DDE para IExplore por si alguien está interesado en esta librería: support.microsoft.com/kb/160957
        He probado el tópico "WWW_Exit" por curiosidad y funciona, pero ninguno de ellos funciona en Firefox (solo los que añadi a la Class de abajo).

Código
  1.    ' nDDE Helper
  2.    ' By Elektro
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'NDDE.dll' library.
  6.    '
  7.    ' Usage Examples:
  8.    ' MessageBox.Show(GetFirefoxUrl())
  9.    ' NavigateFirefox(New Uri("http://www.mozilla.org"), OpenInNewwindow:=False)
  10.  
  11.    ''' <summary>
  12.    ''' Gets the url of the active Tab-page from a running Firefox process.
  13.    ''' </summary>
  14.    ''' <returns>The url of the active Tab-page.</returns>
  15.    Public Function GetFirefoxUrl() As String
  16.  
  17.        Using dde As New DdeClient("Firefox", "WWW_GetWindowInfo")
  18.  
  19.            dde.Connect()
  20.  
  21.            Dim Url As String =
  22.                dde.Request("URL", Integer.MaxValue).
  23.                    Trim({ControlChars.NullChar, ControlChars.Quote, ","c})
  24.  
  25.  
  26.            dde.Disconnect()
  27.  
  28.            Return Url
  29.  
  30.        End Using
  31.  
  32.    End Function
  33.  
  34.    ''' <summary>
  35.    ''' Navigates to an URL in the running Firefox process.
  36.    ''' </summary>
  37.    ''' <param name="url">Indicates the URL to navigate.</param>
  38.    ''' <param name="OpenInNewwindow">
  39.    ''' If set to <c>true</c> the url opens in a new Firefox window, otherwise, the url opens in a new Tab.
  40.    ''' </param>
  41.    Public Sub NavigateFirefox(ByVal url As Uri,
  42.                               ByVal OpenInNewwindow As Boolean)
  43.  
  44.        Dim Address As String = url.AbsoluteUri
  45.  
  46.        If OpenInNewwindow Then
  47.            Address &= ",,0"
  48.        End If
  49.  
  50.        Using dde As New DdeClient("Firefox", "WWW_OpenURL")
  51.  
  52.            dde.Connect()
  53.            dde.Request(Address, Integer.MaxValue)
  54.            dde.Disconnect()
  55.  
  56.        End Using
  57.  
  58.    End Sub
En línea



z3nth10n


Desconectado Desconectado

Mensajes: 1.583


"Jack of all trades, master of none." - Zenthion


Ver Perfil WWW
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #407 en: 8 Agosto 2014, 17:11 pm »

Muy buenas, después de estar bastante tiempo sin subir nada aquí tengo una cosita interesante :P

Creo que algunas de estas utilidades están ya presentes dentro de lo que es la super colección de Elektro, pero bueno supongo que un indentador XML nunca se ha visto por aquí así que aquí va:

Código
  1. Imports System.IO
  2. Imports System.Xml
  3. Imports System.Xml.Serialization
  4.  
  5. Public Class XMLTools
  6.  
  7.    Public Shared Function Serialize(Of T)(value As T, Optional ByVal indented As Boolean = False) As String
  8.        If value Is Nothing Then
  9.            Throw New Exception("XMLSerializer - The value passed is null!")
  10.            Return ""
  11.        End If
  12.        Try
  13.  
  14.            Dim xmlserializer As New XmlSerializer(GetType(T))
  15.            Dim serializeXml As String = ""
  16.  
  17.            Using stringWriter As New StringWriter()
  18.  
  19.                Using writer As XmlWriter = XmlWriter.Create(stringWriter)
  20.                    xmlserializer.Serialize(writer, value)
  21.                    serializeXml = stringWriter.ToString()
  22.                End Using
  23.  
  24.                If indented Then
  25.                    serializeXml = Beautify(serializeXml)
  26.                End If
  27.  
  28.            End Using
  29.  
  30.            Return serializeXml
  31.        Catch ex As Exception
  32.            Throw New Exception(ex.Message)
  33.            Return ""
  34.        End Try
  35.    End Function
  36.  
  37.    Public Shared Function Deserialize(Of T)(value As String) As T
  38.  
  39.        Try
  40.            Dim returnvalue As New Object()
  41.            Dim xmlserializer As New XmlSerializer(GetType(T))
  42.            Dim reader As TextReader = New StringReader(value)
  43.  
  44.            returnvalue = xmlserializer.Deserialize(reader)
  45.  
  46.            reader.Close()
  47.            Return DirectCast(returnvalue, T)
  48.        Catch ex As Exception
  49.            Throw New Exception(ex.Message)
  50.            Return Nothing
  51.        End Try
  52.  
  53.    End Function
  54.  
  55.    Public Shared Sub SerializeToFile(Of T)(value As T, filePath As String, Optional ByVal indented As Boolean = False)
  56.        If value Is Nothing Then
  57.            Throw New Exception("XMLSerializer - The value passed is null!")
  58.        End If
  59.        Try
  60.            Dim xmlserializer As New XmlSerializer(GetType(T))
  61.            Using fileWriter As StreamWriter = New StreamWriter(filePath)
  62.                If indented Then
  63.                    Using stringWriter As New StringWriter()
  64.                        Using writer As XmlWriter = XmlWriter.Create(stringWriter)
  65.                            xmlserializer.Serialize(writer, value)
  66.                            fileWriter.WriteLine(Beautify(stringWriter.ToString()))
  67.                        End Using
  68.                    End Using
  69.                Else
  70.                    Using writer As XmlWriter = XmlWriter.Create(fileWriter)
  71.                        xmlserializer.Serialize(writer, value)
  72.                    End Using
  73.                End If
  74.            End Using
  75.  
  76.        Catch ex As Exception
  77.            Throw New Exception(ex.Message)
  78.        End Try
  79.    End Sub
  80.  
  81.    Public Shared Function DeserializeFromFile(Of T)(filePath As String) As T
  82.  
  83.        Try
  84.            Dim returnvalue As New Object()
  85.            Dim xmlserializer As New XmlSerializer(GetType(T))
  86.            Using reader As TextReader = New StreamReader(filePath)
  87.                returnvalue = xmlserializer.Deserialize(reader)
  88.            End Using
  89.            Return DirectCast(returnvalue, T)
  90.        Catch ex As Exception
  91.            Throw New Exception(ex.Message)
  92.            Return Nothing
  93.        End Try
  94.  
  95.    End Function
  96.  
  97.    Public Shared Function Beautify(obj As Object) As String
  98.        Dim doc As New XmlDocument()
  99.        If obj.[GetType]() Is GetType(String) Then
  100.            If Not [String].IsNullOrEmpty(DirectCast(obj, String)) Then
  101.                Try
  102.                    doc.LoadXml(DirectCast(obj, String))
  103.                Catch ex As Exception
  104.                    Throw New Exception("XMLIndenter - Wrong string format! [" + ex.Message & "]")
  105.                    Return ""
  106.                End Try
  107.            Else
  108.                Throw New Exception("XMLIndenter - String is null!")
  109.                Return ""
  110.            End If
  111.        ElseIf obj.[GetType]() Is GetType(XmlDocument) Then
  112.            doc = DirectCast(obj, XmlDocument)
  113.        Else
  114.            Throw New Exception("XMLIndenter - Not supported type!")
  115.            Return ""
  116.        End If
  117.        Dim returnValue As String = ""
  118.        Using w As New MemoryStream()
  119.            Using writer As New XmlTextWriter(w, Encoding.Unicode)
  120.                writer.Formatting = Formatting.Indented
  121.                doc.WriteContentTo(writer)
  122.  
  123.                writer.Flush()
  124.                w.Seek(0L, SeekOrigin.Begin)
  125.  
  126.                Using reader As New StreamReader(w)
  127.                    returnValue = reader.ReadToEnd()
  128.                End Using
  129.            End Using
  130.        End Using
  131.    End Function
  132.  
  133. End Class

Un saludo.
« Última modificación: 8 Agosto 2014, 21:06 pm por Ikillnukes » En línea


Interesados hablad por Discord.
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #408 en: 8 Agosto 2014, 18:11 pm »

Creo que algunas de estas utilidades están ya presentes dentro de lo que es la super colección de Elektro, pero bueno supongo que un indentador XML nunca se ha visto por aquí así que aquí va:

precisamente estoy harto de que cierta utilidad de Microsoft me genere los archivos de manifiesto sin ningún tipo de indentación, esto me sirve ;).

EDITO: en un principio iba a ahorrarme comentarios sobre posibles mejoras de código o etc, pero hay un fallo importante que se debe corregir, no estás liberando el memorystream:
Citar
Código
  1. Dim w As New MemoryStream()

Ni tampoco el Writer ni el Reader xD

Por cierto la Class XMLTextWriter está obsoleta, en su defecto Microsoft recomienda el uso de XMLWriter.

EDITO 2: Me he tomado la libertad de editar el código original enfocándolo de otra manera (aunque tampoco es tan distinto):

Ejemplo de uso:

Código
  1.        Dim TextEncoding As System.Text.Encoding = System.Text.Encoding.Default
  2.        Dim UnformattedXMLDocument As String = IO.File.ReadAllText("C:\Unformatted Document.xml", TextEncoding)
  3.        Dim FormattedXMLDocument As String = XMLBeautify(XMLText:=UnformattedXMLDocument,
  4.                                                         IndentChars:=New String(" "c, 2),
  5.                                                         IndentOnAttributes:=False,
  6.                                                         TextEncoding:=TextEncoding)
  7.  
  8.        IO.File.WriteAllText("C:\Formatted Document.xml", FormattedXMLDocument, TextEncoding)


Snippet:

Código
  1.    ''' <summary>
  2.    ''' Beautifies the contents of an unindented XML document.
  3.    ''' </summary>
  4.    ''' <param name="XMLText">
  5.    ''' The XML text content.
  6.    ''' It can be an entire document or a fragment.
  7.    ''' </param>
  8.    ''' <param name="IndentChars">
  9.    ''' The string that is used to indent the XML.
  10.    ''' Default value is: <see cref="ControlChars.Tab"/>
  11.    ''' </param>
  12.    ''' <param name="IndentOnAttributes">
  13.    ''' If set to <c>true</c>, attributes will be separated by newlines.
  14.    ''' Default value is: <c>false</c>
  15.    ''' </param>
  16.    ''' <param name="TextEncoding">
  17.    ''' The XML text encoding to use.
  18.    ''' Default value is: <see cref="System.Text.Encoding.Default"/>.
  19.    ''' </param>
  20.    ''' <returns>The beautified XML text.</returns>
  21.    ''' <exception cref="System.ArgumentNullException"></exception>
  22.    Public Shared Function XMLBeautify(ByVal XMLText As String,
  23.                                       Optional ByVal IndentChars As String = Nothing,
  24.                                       Optional ByVal IndentOnAttributes As Boolean = False,
  25.                                       Optional ByVal TextEncoding As System.Text.Encoding = Nothing) As String
  26.  
  27.        If String.IsNullOrEmpty(XMLText) Then
  28.            Throw New ArgumentNullException(XMLText)
  29.        End If
  30.  
  31.        Dim sb As New System.Text.StringBuilder
  32.        Dim doc As New Xml.XmlDocument()
  33.        Dim settings As New Xml.XmlWriterSettings
  34.  
  35.        With settings
  36.            .Indent = True
  37.            .CheckCharacters = True
  38.            .OmitXmlDeclaration = False
  39.            .ConformanceLevel = Xml.ConformanceLevel.Auto
  40.            .NamespaceHandling = Xml.NamespaceHandling.Default
  41.            .NewLineHandling = Xml.NewLineHandling.Replace
  42.            .NewLineChars = ControlChars.NewLine
  43.            .NewLineOnAttributes = IndentOnAttributes
  44.            .IndentChars = If(IndentChars IsNot Nothing, IndentChars, ControlChars.Tab)
  45.            .Encoding = If(TextEncoding IsNot Nothing, TextEncoding, System.Text.Encoding.Default)
  46.        End With
  47.  
  48.        Using writer As Xml.XmlWriter = Xml.XmlWriter.Create(sb, settings)
  49.            doc.LoadXml(XMLText)
  50.            doc.WriteContentTo(writer)
  51.            writer.Flush()
  52.            Return sb.ToString
  53.        End Using
  54.  
  55.    End Function
  56.  
  57.    ''' <summary>
  58.    ''' Beautifies the contents of an unindented XML document.
  59.    ''' </summary>
  60.    ''' <param name="XMLFile">
  61.    ''' An <see cref="T:IO.FileInfo"/> that contains the XML info.
  62.    ''' It can be an entire document or a fragment.
  63.    ''' </param>
  64.    ''' <param name="IndentChars">
  65.    ''' The string that is used to indent the XML.
  66.    ''' Default value is: <see cref="ControlChars.Tab"/>
  67.    ''' </param>
  68.    ''' <param name="IndentOnAttributes">
  69.    ''' If set to <c>true</c>, attributes will be separated by newlines.
  70.    ''' Default value is: <c>false</c>
  71.    ''' </param>
  72.    ''' <param name="TextEncoding">
  73.    ''' The XML text encoding to use.
  74.    ''' Default value is: <see cref="System.Text.Encoding.Default"/>.
  75.    ''' </param>
  76.    ''' <returns>The beautified XML text.</returns>
  77.    ''' <exception cref="System.ArgumentNullException"></exception>
  78.    Public Shared Function XMLBeautify(XMLFile As IO.FileInfo,
  79.                                       Optional ByVal IndentChars As String = Nothing,
  80.                                       Optional ByVal IndentOnAttributes As Boolean = False,
  81.                                       Optional ByVal TextEncoding As System.Text.Encoding = Nothing) As String
  82.  
  83.        Return XMLBeautify(IO.File.ReadAllText(XMLFile.FullName, TextEncoding), IndentChars, IndentOnAttributes, TextEncoding)
  84.  
  85.    End Function



Posibles outputs:

1º:

Código
  1. <savedata>
  2.  <SoftwareType>Freeware</SoftwareType>
  3.  <SoftwareID>Moo0 FileMonitor</SoftwareID>
  4.  <Version>1.11</Version>
  5.  <MainWindow>
  6.    <SoftwareType>Freeware</SoftwareType>
  7.    <SoftwareID>Moo0 FileMonitor</SoftwareID>
  8.    <Version>1.11</Version>
  9.    <View F="0" E="0" D="0" RefreshFrequency="500" LogUpTo="20000" EasyDrag="1" Maximized="0" X="958" Y="453" Width="962" Height="585" KeepOnTop="0"></View>
  10.    <ChangesColumnOrder length="6" _0="0" _1="1" _2="2" _3="3" _4="4" _5="5"></ChangesColumnOrder>
  11.  </MainWindow>
  12.  <Skin>Classic LG</Skin>
  13. </savedata>


2º:
Código
  1. <savedata>
  2.  <SoftwareType>Freeware</SoftwareType>
  3.  <SoftwareID>Moo0 FileMonitor</SoftwareID>
  4.  <Version>1.11</Version>
  5.  <MainWindow>
  6.    <SoftwareType>Freeware</SoftwareType>
  7.    <SoftwareID>Moo0 FileMonitor</SoftwareID>
  8.    <Version>1.11</Version>
  9.    <View
  10.      F="0"
  11.      E="0"
  12.      D="0"
  13.      RefreshFrequency="500"
  14.      LogUpTo="20000"
  15.      EasyDrag="1"
  16.      Maximized="0"
  17.      X="958"
  18.      Y="453"
  19.      Width="962"
  20.      Height="585"
  21.      KeepOnTop="0"></View>
  22.    <ChangesColumnOrder
  23.      length="6"
  24.      _0="0"
  25.      _1="1"
  26.      _2="2"
  27.      _3="3"
  28.      _4="4"
  29.      _5="5"></ChangesColumnOrder>
  30.  </MainWindow>
  31.  <Skin>Classic LG</Skin>
  32. </savedata>

Saludos
« Última modificación: 8 Agosto 2014, 20:52 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.874



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #409 en: 8 Agosto 2014, 20:59 pm »

Ejemplo de como implementar la interface ISerializable e IXMLSerializable:

Código
  1. #Region " Imports "
  2.  
  3. Imports System.Runtime.Serialization
  4. Imports System.Security.Permissions
  5. Imports System.Xml.Serialization
  6. Imports System.Xml
  7.  
  8. #End Region
  9.  
  10. ''' <summary>
  11. ''' SerializableClassTest.
  12. ''' This class can be serialized.
  13. ''' </summary>
  14. <Serializable>
  15. <XmlRoot("SerializableClassTest")>
  16. Public Class SerializableClassTest : Implements ISerializable : Implements IXmlSerializable
  17.  
  18. #Region "Properties"
  19.  
  20.    Public Property StrValue As String
  21.    Public Property Int32Value As Integer
  22.  
  23. #End Region
  24.  
  25. #Region "Constructors"
  26.  
  27.    ''' <summary>
  28.    ''' Prevents a default instance of the <see cref="SerializableClassTest"/> class from being created.
  29.    ''' </summary>
  30.    Private Sub New()
  31.    End Sub
  32.  
  33.    ''' <summary>
  34.    ''' Initializes a new instance of the <see cref="SerializableClassTest"/> class.
  35.    ''' </summary>
  36.    Public Sub New(ByVal StrValue As String,
  37.                   ByVal Int32Value As Integer)
  38.  
  39.        Me.StrValue = StrValue
  40.        Me.Int32Value = Int32Value
  41.  
  42.    End Sub
  43.  
  44. #End Region
  45.  
  46. #Region "ISerializable implementation" ' For Binary serialization.
  47.  
  48.    ''' <summary>
  49.    ''' Populates a <see cref="T:SerializationInfo"/> with the data needed to serialize the target object.
  50.    ''' </summary>
  51.    ''' <param name="info">The <see cref="T:SerializationInfo"/> to populate with data.</param>
  52.    ''' <param name="context">The destination (see <see cref="T:StreamingContext"/>) for this serialization.</param>
  53.    <SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.SerializationFormatter)>
  54.    Protected Overridable Sub GetObjectData(ByVal info As SerializationInfo,
  55.                                            ByVal context As StreamingContext) Implements ISerializable.GetObjectData
  56.  
  57.        If info Is Nothing Then
  58.            Throw New ArgumentNullException("info")
  59.        End If
  60.  
  61.        With info
  62.  
  63.            .AddValue("PropertyName1", Me.StrValue, Me.StrValue.GetType)
  64.            .AddValue("PropertyName2", Me.Int32Value, Me.Int32Value.GetType)
  65.  
  66.        End With
  67.  
  68.    End Sub
  69.  
  70.    ''' <summary>
  71.    ''' Initializes a new instance of the <see cref="SerializableClassTest"/> class.
  72.    ''' This constructor is used to deserialize values.
  73.    ''' </summary>
  74.    ''' <param name="info">The information.</param>
  75.    ''' <param name="context">The context.</param>
  76.    Protected Sub New(ByVal info As SerializationInfo,
  77.                      ByVal context As StreamingContext)
  78.  
  79.        If info Is Nothing Then
  80.            Throw New ArgumentNullException("info")
  81.        End If
  82.  
  83.        Me.StrValue = info.GetString("PropertyName1")
  84.        Me.Int32Value = info.GetInt32("PropertyName2")
  85.  
  86.    End Sub
  87.  
  88. #End Region
  89.  
  90. #Region "IXMLSerializable implementation" ' For XML serialization.
  91.  
  92.    ''' <summary>
  93.    ''' This method is reserved and should not be used.
  94.    ''' When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method,
  95.    ''' and instead, if specifying a custom schema is required, apply the <see cref="T:XmlSchemaProviderAttribute"/> to the class.
  96.    ''' </summary>
  97.    ''' <returns>
  98.    ''' An <see cref="T:Xml.Schema.XmlSchema"/> that describes the XML representation of the object
  99.    ''' that is produced by the <see cref="M:IXmlSerializable.WriteXml(Xml.XmlWriter)"/> method
  100.    ''' and consumed by the <see cref="M:IXmlSerializable.ReadXml(Xml.XmlReader)"/> method.
  101.    ''' </returns>
  102.    Public Function GetSchema() As Schema.XmlSchema Implements IXmlSerializable.GetSchema
  103.  
  104.        Return Nothing
  105.  
  106.    End Function
  107.  
  108.    ''' <summary>
  109.    ''' Converts an object into its XML representation.
  110.    ''' </summary>
  111.    ''' <param name="writer">The <see cref="T:Xml.XmlWriter"/> stream to which the object is serialized.</param>
  112.    Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml
  113.  
  114.        writer.WriteElementString("PropertyName1", Me.StrValue)
  115.        writer.WriteElementString("PropertyName2", CStr(Me.Int32Value))
  116.  
  117.    End Sub
  118.  
  119.    ''' <summary>
  120.    ''' Generates an object from its XML representation.
  121.    ''' </summary>
  122.    ''' <param name="reader">The <see cref="T:Xml.XmlReader"/> stream from which the object is deserialized.</param>
  123.    Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml
  124.  
  125.        With reader
  126.  
  127.            .ReadStartElement(MyBase.GetType.Name)
  128.  
  129.            Me.StrValue = .ReadElementContentAsString
  130.            Me.Int32Value = .ReadElementContentAsInt
  131.  
  132.        End With
  133.  
  134.    End Sub
  135.  
  136. #End Region
  137.  
  138. End Class



Ejemplo de como usar la Class DeviceWatcher en un WinForms, sirve para detectar los eventos de inserción/extracción de los dispositivos, quizás se pueda utilizar como reemplazamiento del típico código de WMI para monitorizar USB's, pero todavía no le he podido sacar todo el jugo al asunto, poca documentación...

Código
  1. #Region " Instructions "
  2.  
  3.  
  4. ' 1. Create a new WinForms project targeting .NET Framework 4.5.
  5.  
  6.  
  7. ' 2. Close VisualStudio, open the 'YourProjectName.vbproj' file in a text-editor and add this property:
  8. ' *****************************************************************************************************
  9. '<PropertyGroup>
  10. '    ...
  11. '    <TargetPlatformVersion>8.0</TargetPlatformVersion>
  12. '    ...
  13. '</PropertyGroup>
  14.  
  15.  
  16. ' 3. Load the project in VisualStudio, open the 'References' menu and add these references:
  17. ' *****************************************************************************************
  18. ' C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades\System.Runtime.dll
  19. ' C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades\System.Runtime.InteropServices.WindowsRuntime.dll
  20.  
  21.  
  22. ' 4. In the 'References' menu, go to 'Windows > Core' tab and add these references:
  23. ' *********************************************************************************
  24. ' Windows.Devices
  25. ' Windows.Foundation
  26.  
  27.  
  28. #End Region
  29.  
  30. #Region " Imports "
  31.  
  32. Imports Windows.Devices.Enumeration
  33. Imports Windows.Foundation
  34.  
  35. #End Region
  36.  
  37. Public Class DeviceWatcher_Test
  38.  
  39.    Friend WithEvents dw As DeviceWatcher = DeviceInformation.CreateWatcher
  40.  
  41.    Private Sub Test() Handles MyBase.Load
  42.  
  43.        dw.Start()
  44.  
  45.    End Sub
  46.  
  47.    ''' <summary>
  48.    ''' Event that is raised when a device is added to the collection enumerated by the DeviceWatcher.
  49.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.added.aspx
  50.    ''' </summary>
  51.    ''' <param name="sender">The source of the event.</param>
  52.    ''' <param name="e">The <see cref="DeviceInformation"/> instance containing the event data.</param>
  53.    Private Sub dw_Added(ByVal sender As DeviceWatcher, ByVal e As DeviceInformation) _
  54.    Handles dw.Added
  55.  
  56.        Dim sb As New System.Text.StringBuilder
  57.  
  58.        With sb
  59.            .AppendLine("dw_added")
  60.            .AppendLine("********")
  61.            .AppendLine(String.Format("Interface ID.: {0}", e.Id))
  62.            .AppendLine(String.Format("Friendly Name: {0}", e.Name))
  63.            .AppendLine(String.Format("Is Enabled?..: {0}", e.IsEnabled))
  64.  
  65.            If e.Properties IsNot Nothing Then
  66.  
  67.                For Each item As KeyValuePair(Of String, Object) In e.Properties
  68.  
  69.                    If item.Value IsNot Nothing Then
  70.  
  71.                        .AppendLine(String.Format("TKey:{0}, TVal:{1} (TVal Type:{2})",
  72.                                                  item.Key, item.Value.ToString, item.Value.GetType.Name))
  73.  
  74.                    End If
  75.  
  76.                Next
  77.  
  78.            End If
  79.  
  80.        End With
  81.  
  82.        Debug.WriteLine(sb.ToString)
  83.  
  84.    End Sub
  85.  
  86.    ''' <summary>
  87.    ''' Event that is raised when a device is removed from the collection of enumerated devices.
  88.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.removed.aspx
  89.    ''' </summary>
  90.    ''' <param name="sender">The source of the event.</param>
  91.    ''' <param name="e">The <see cref="DeviceInformationUpdate"/> instance containing the event data.</param>
  92.    Private Sub dw_Removed(ByVal sender As DeviceWatcher, ByVal e As DeviceInformationUpdate) _
  93.    Handles dw.Removed
  94.  
  95.        Dim sb As New System.Text.StringBuilder
  96.  
  97.        With sb
  98.            .AppendLine("dw_Removed")
  99.            .AppendLine("**********")
  100.            .AppendLine(String.Format("Interface ID:{0}", e.Id))
  101.  
  102.            For Each item As KeyValuePair(Of String, Object) In e.Properties
  103.                .AppendLine(String.Format("TKey:{0}, TVal:{1} (TVal Type:{2})",
  104.                                          item.Key, item.Value.ToString, item.Value.GetType.Name))
  105.            Next
  106.  
  107.        End With
  108.  
  109.        Debug.WriteLine(sb.ToString)
  110.  
  111.    End Sub
  112.  
  113.    ''' <summary>
  114.    ''' Event that is raised when a device is updated in the collection of enumerated devices.
  115.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.updated.aspx
  116.    ''' </summary>
  117.    ''' <param name="sender">The source of the event.</param>
  118.    ''' <param name="e">The <see cref="DeviceInformationUpdate"/> instance containing the event data.</param>
  119.    Private Sub dw_Updated(ByVal sender As DeviceWatcher, ByVal e As DeviceInformationUpdate) _
  120.    Handles dw.Updated
  121.  
  122.        Dim sb As New System.Text.StringBuilder
  123.  
  124.        With sb
  125.            .AppendLine("dw_Updated")
  126.            .AppendLine("**********")
  127.            .AppendLine(String.Format("Interface ID: {0}", e.Id))
  128.  
  129.            For Each item As KeyValuePair(Of String, Object) In e.Properties
  130.  
  131.                If item.Key.EndsWith("InterfaceEnabled", StringComparison.OrdinalIgnoreCase) Then
  132.                    Dim Result As Boolean = CBool(item.Value)
  133.                    .AppendLine(String.Format("The device is accessible?:{0}", CStr(Result)))
  134.  
  135.                Else
  136.                    .AppendLine(String.Format("TKwy:{0}, TVal:{1} (TVal Type:{2})",
  137.                                              item.Key, item.Value.ToString, item.Value.GetType.Name))
  138.  
  139.                End If
  140.  
  141.            Next
  142.  
  143.        End With
  144.  
  145.        Debug.WriteLine(sb.ToString)
  146.  
  147.    End Sub
  148.  
  149.    ''' <summary>
  150.    ''' Event that is raised when the enumeration operation has been stopped.
  151.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.stopped.aspx
  152.    ''' </summary>
  153.    ''' <param name="sender">The source of the event.</param>
  154.    ''' <param name="e">The object containing the event data.</param>
  155.    Private Sub dw_Stopped(ByVal sender As DeviceWatcher, ByVal e As Object) _
  156.    Handles dw.Stopped
  157.  
  158.        Dim sb As New System.Text.StringBuilder
  159.  
  160.        With sb
  161.            .AppendLine("dw_Stopped")
  162.            .AppendLine("**********")
  163.            .AppendLine(String.Format("e:{1} (e Type:{2})",
  164.                                      e.ToString, e.GetType.Name))
  165.  
  166.        End With
  167.  
  168.        Debug.WriteLine(sb.ToString)
  169.  
  170.    End Sub
  171.  
  172.    ''' <summary>
  173.    ''' Event that is raised when the enumeration of devices completes.
  174.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.enumerationcompleted.aspx
  175.    ''' </summary>
  176.    ''' <param name="sender">The source of the event.</param>
  177.    ''' <param name="e">The object containing the event data.</param>
  178.    Private Sub dw_EnumerationCompleted(ByVal sender As DeviceWatcher, ByVal e As Object) _
  179.    Handles dw.EnumerationCompleted
  180.  
  181.        If e IsNot Nothing Then
  182.  
  183.            Dim sb As New System.Text.StringBuilder
  184.  
  185.            With sb
  186.                .AppendLine("EnumerationCompleted")
  187.                .AppendLine("********************")
  188.                .AppendLine(String.Format("e:{1} (e Type:{2})",
  189.                                          e.ToString, e.GetType.Name))
  190.  
  191.            End With
  192.  
  193.            Debug.WriteLine(sb.ToString)
  194.  
  195.        End If
  196.  
  197.    End Sub
  198.  
  199. End Class
  200.  
« Última modificación: 8 Agosto 2014, 21:04 pm por Eleкtro » En línea



Páginas: 1 ... 26 27 28 29 30 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 ... 60 Ir Arriba Respuesta Imprimir 

Ir a:  

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