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

 

 


Tema destacado: Los 10 CVE más críticos (peligrosos) de 2020


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 2 Visitantes están viendo este tema.
Páginas: 1 ... 20 21 22 23 24 25 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 ... 58 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 480,105 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #340 en: 13 Noviembre 2013, 06:36 am »

El equivalente al sizeof de C#:

Código
  1. #Region " SizeOf "
  2.  
  3.    ' [ SizeOf ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(SizeOf(1L))      ' Result: 8
  10.    ' MsgBox(SizeOf(Of Long)) ' Result: 8
  11.  
  12.    Public Function SizeOf(Of T)() As Integer
  13.  
  14.        Try
  15.            Return System.Runtime.InteropServices.Marshal.SizeOf(GetType(T))
  16.        Catch ex As ArgumentException
  17.            Return -1
  18.        End Try
  19.  
  20.    End Function
  21.  
  22.    Public Function SizeOf(ByVal [Object] As Object) As Integer
  23.  
  24.        Try
  25.            Return System.Runtime.InteropServices.Marshal.SizeOf([Object])
  26.        Catch ex As ArgumentNullException
  27.            Return -1
  28.        Catch ex As ArgumentException
  29.            Return -1
  30.        End Try
  31.  
  32.    End Function
  33.  
  34. #End Region





Una forma sencilla de obtener el HBitmap de una imagen no Bitmap (util para añadirlo a un módulo de extensiones)...

Código
  1.        Dim Hbitmap As IntPtr = CType(PictureBox1.Image, Bitmap).GetHbitmap()
  2.        PictureBox2.BackgroundImage = Image.FromHbitmap(Hbitmap)

Código
  1.    Private Function Get_Image_HBitmap(ByVal Image As Image) As IntPtr
  2.        Return CType(Image, Bitmap).GetHbitmap()
  3.    End Function


« Última modificación: 13 Noviembre 2013, 15:47 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #341 en: 17 Noviembre 2013, 14:43 pm »

Un pequeño código para facilitar la tarea de preservar las fechas de un archivo, por ejemplo cuando se modifica el texto de un archivo, o cuando se convierte un archivo de audio (al mismo u otro formato).

El modo de empleo es muy sencillo:

Código
  1. FileDate.Action("C:\File.txt", FileDate.FileDateAction.Save)
  2. IO.File.AppendAllText("C:\File.txt", "Hello World!")
  3. FileDate.Action("C:\File.txt", FileDate.FileDateAction.Restore)

O bien:

Código
  1. FileDate.Action("C:\File.txt", FileDate.FileDateAction.Save, False)
  2. IO.File.AppendAllText("C:\File.txt", "Hello World!")
  3. IO.File.Move("C:\File.txt", "C:\File.log")
  4. FileDate.Action(New IO.FileInfo("C:\File.log"), FileDate.FileDateAction.Restore, False)



Código
  1. #Region " Preserve FileDate "
  2.  
  3. ' [ Preserve FileDate ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Usage Examples:
  8.  
  9. ' // Example 1:
  10. '
  11. ' FileDate.Action("C:\File.txt", FileDate.FileDateAction.Save)
  12. ' IO.File.AppendAllText("C:\File.txt", "Hello World!")
  13. ' FileDate.Action("C:\File.txt", FileDate.FileDateAction.Restore)
  14.  
  15. ' // Example 2:
  16. '
  17. ' FileDate.Action("C:\File.txt", FileDate.FileDateAction.Save, False)
  18. ' IO.File.AppendAllText("C:\File.txt", "Hello World!")
  19. ' IO.File.Move("C:\File.txt", "C:\File.log")
  20. ' FileDate.Action(New IO.FileInfo("C:\File.log"), FileDate.FileDateAction.Restore, False)
  21.  
  22. Public Class FileDate
  23.  
  24.    ''' <summary>
  25.    ''' Collection that contains the files and their dates.
  26.    ''' </summary>
  27.    Private Shared FileDates As New Dictionary(Of String, Date())
  28.  
  29.    ''' <summary>
  30.    ''' Stores the File object.
  31.    ''' </summary>
  32.    Private Shared _File As IO.FileInfo
  33.  
  34.    ''' <summary>
  35.    ''' Stores the full path of the file
  36.    ''' </summary>
  37.    Private Shared FullPath As String
  38.  
  39.    ''' <summary>
  40.    ''' An action to take on file dates.
  41.    ''' </summary>
  42.    Public Enum FileDateAction As Short
  43.  
  44.        ''' <summary>
  45.        ''' Save file dates into filedates collection.
  46.        ''' </summary>
  47.        Save = 0
  48.  
  49.        ''' <summary>
  50.        ''' Restore file dates from filedates collection.
  51.        ''' </summary>
  52.        Restore = 1
  53.  
  54.        ''' <summary>
  55.        ''' Remove file dates from filedates collection,
  56.        ''' this don't removes the dates from file.
  57.        ''' </summary>
  58.        Remove = 2
  59.  
  60.        ''' <summary>
  61.        ''' Sets the file dates of specified file to "01/01/1800 00:00:00"
  62.        ''' </summary>
  63.        Truncate = 3
  64.  
  65.    End Enum
  66.  
  67.    ''' <summary>
  68.    ''' Performs an action on the dates of the specified file,
  69.    ''' Creation Date, LastAccess Date and LastWrite Date.
  70.    ''' </summary>
  71.    ''' <param name="File">
  72.    ''' The File.
  73.    ''' </param>
  74.    ''' <param name="Action">
  75.    ''' The action to take on file dates.
  76.    ''' </param>
  77.    ''' <param name="IncludeFileExtension">
  78.    ''' Specifies if that the filename extension should be included or not.
  79.    ''' Default value is <paramref name="True"/>.
  80.    ''' This parameter should be set to <paramref name="False"/>  when renaming files.
  81.    ''' </param>
  82.    Public Shared Sub Action(ByVal File As IO.FileInfo,
  83.                             ByVal Action As FileDateAction,
  84.                             Optional ByVal IncludeFileExtension As Boolean = True)
  85.  
  86.        _File = File
  87.        DoFileDateAction(_File, Action, IncludeFileExtension)
  88.  
  89.    End Sub
  90.  
  91.    ''' <summary>
  92.    ''' Performs an action on the dates of the specified file,
  93.    ''' Creation Date, LastAccess Date and LastWrite Date.
  94.    ''' </summary>
  95.    ''' <param name="File">
  96.    ''' The File.
  97.    ''' </param>
  98.    ''' <param name="Action">
  99.    ''' The action to take on file dates.
  100.    ''' </param>
  101.    ''' <param name="IncludeFileExtension">
  102.    ''' Specifies if that the filename extension should be included or not.
  103.    ''' Default value is <paramref name="True"/>.
  104.    ''' This parameter should be set to <paramref name="False"/> when renaming files.
  105.    ''' </param>
  106.    Public Shared Sub Action(ByVal File As String,
  107.                             ByVal Action As FileDateAction,
  108.                             Optional ByVal IncludeFileExtension As Boolean = True)
  109.  
  110.        _File = New IO.FileInfo(File)
  111.        DoFileDateAction(_File, Action, IncludeFileExtension)
  112.  
  113.    End Sub
  114.  
  115.    ''' <summary>
  116.    ''' Clears all the dates stored in the filedates collection.
  117.    ''' </summary>
  118.    Public Shared Sub ClearFileDateCollection()
  119.        FileDates.Clear()
  120.    End Sub
  121.  
  122.    ''' <summary>
  123.    ''' Perform an action to take on file dates.
  124.    ''' </summary>
  125.    Private Shared Sub DoFileDateAction(ByVal File As IO.FileInfo,
  126.                                        ByVal Action As FileDateAction,
  127.                                        ByVal IncludeFileExtension As Boolean)
  128.  
  129.        FullPath = If(IncludeFileExtension,
  130.                      File.FullName,
  131.                      If(File.Name.Contains("."),
  132.                         File.FullName.Substring(0, File.FullName.LastIndexOf(".")),
  133.                         File.FullName))
  134.  
  135.        HandleErrors(Action)
  136.  
  137.        Select Case Action
  138.  
  139.            Case FileDateAction.Save
  140.  
  141.                FileDates.Add(FullPath,
  142.                             {File.CreationTime, File.LastAccessTime, File.LastWriteTime})
  143.  
  144.            Case FileDateAction.Restore
  145.  
  146.                File.CreationTime = FileDates(FullPath).First
  147.                File.LastAccessTime = FileDates(FullPath)(1)
  148.                File.LastWriteTime = FileDates(FullPath).Last
  149.  
  150.                FileDates.Remove(FullPath)
  151.  
  152.            Case FileDateAction.Remove
  153.  
  154.                FileDates.Remove(FullPath)
  155.  
  156.            Case FileDateAction.Truncate
  157.                File.CreationTime = "01/01/1800 00:00:00"
  158.                File.LastAccessTime = "01/01/1800 00:00:00"
  159.                File.LastWriteTime = "01/01/1800 00:00:00"
  160.  
  161.        End Select
  162.  
  163.    End Sub
  164.  
  165.    ''' <summary>
  166.    ''' Simple Error Handling.
  167.    ''' </summary>
  168.    Private Shared Sub HandleErrors(ByVal Action As FileDateAction)
  169.  
  170.        Select Case Action
  171.  
  172.            Case FileDateAction.Save
  173.  
  174.                If FileDates.ContainsKey(FullPath) Then
  175.                    Throw New Exception("File already exist in collection.")
  176.                End If
  177.  
  178.            Case FileDateAction.Restore, FileDateAction.Remove
  179.  
  180.                If Not FileDates.ContainsKey(FullPath) Then
  181.                    Throw New Exception("File not found in collection.")
  182.                End If
  183.  
  184.        End Select
  185.  
  186.  
  187.    End Sub
  188.  
  189. End Class
  190.  
  191. #End Region


« Última modificación: 17 Noviembre 2013, 14:52 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #342 en: 19 Noviembre 2013, 20:04 pm »

Mi implementación de la librería MediaInfo.dll en VBNET: http://pastebin.com/XGUwW8hQ

« Última modificación: 19 Noviembre 2013, 20:07 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #343 en: 19 Noviembre 2013, 20:13 pm »

Shortcut Manager

Resuelve el target de shortcut "corrupto", crea un nuevo shortcut u obtiene información de un shortcut.

Código
  1. Imports System.Runtime.InteropServices
  2. Imports System.Text
  3. Imports System.IO
  4.  
  5. #Region " ShortcutManager "
  6.  
  7. ' [ ShortcutManager ]
  8. '
  9. ' // By Elektro H@cker
  10.  
  11. #Region " Usage Examples "
  12.  
  13. 'Private Sub Test()
  14.  
  15. '    ' Tries to resolve a shortcut which has changed their Target location.
  16. '    ShortcutManager.Resolve_Ui("C:\Truncated Shortcut.lnk", New IntPtr(1))
  17. '    ShortcutManager.Resolve_NoUi("C:\Truncated Shortcut.lnk")
  18.  
  19. '    ' Creates a new Shortcut file
  20. '    ShortcutManager.Create("C:\Shortcut.lnk",
  21. '                           "C:\TargetFile.ext",
  22. '                           "C:\",
  23. '                           "Description",
  24. '                           "-Arguments",
  25. '                           "C:\Icon.ico", 0,
  26. '                           ShortcutManager.HotkeyModifiers.ALT Or ShortcutManager.HotkeyModifiers.CONTROL,
  27. '                           Keys.F1,
  28. '                           ShortcutManager.ShortcutWindowState.Normal)
  29.  
  30. '    ' Gets Shortcut file information
  31. '    Dim ShortcutInfo As ShortcutManager.ShortcutInfo =
  32. '        ShortcutManager.GetInfo("C:\Shortcut.lnk")
  33.  
  34. '    Dim sb As New System.Text.StringBuilder
  35.  
  36. '    With ShortcutInfo
  37.  
  38. '        sb.AppendLine(String.Format(" ""{0}"" ", .ShortcutFile))
  39. '        sb.AppendLine(String.Format("------------------------"))
  40. '        sb.AppendLine(String.Format("Description: {0}", .Description))
  41. '        sb.AppendLine(String.Format("Target: {0}", .Target))
  42. '        sb.AppendLine(String.Format("Arguments: {0}", .Arguments))
  43. '        sb.AppendLine(String.Format("Target Is Directory?: {0}", CStr(.IsDirectory)))
  44. '        sb.AppendLine(String.Format("Target Is File?: {0}", CStr(.IsFile)))
  45. '        sb.AppendLine(String.Format("WorkingDir: {0}", .WorkingDir))
  46. '        sb.AppendLine(String.Format("DirectoryName: {0}", .DirectoryName))
  47. '        sb.AppendLine(String.Format("FileName: {0}", .FileName))
  48. '        sb.AppendLine(String.Format("FileExtension: {0}", .FileExtension))
  49. '        sb.AppendLine(String.Format("DriveLetter: {0}", .DriveLetter))
  50. '        sb.AppendLine(String.Format("Icon: {0}", .Icon))
  51. '        sb.AppendLine(String.Format("Icon Index: {0}", CStr(.IconIndex)))
  52. '        sb.AppendLine(String.Format("Hotkey (Hex): {0}", CStr(.Hotkey)))
  53. '        sb.AppendLine(String.Format("Hotkey (Str): {0} + {1}", .Hotkey_Modifier.ToString, .Hotkey_Key.ToString))
  54. '        sb.AppendLine(String.Format("Window State: {0}", .WindowState.ToString))
  55.  
  56. '    End With
  57.  
  58. '    MsgBox(sb.ToString)
  59.  
  60. 'End Sub
  61.  
  62. #End Region
  63.  
  64. Public Class ShortcutManager
  65.  
  66. #Region " Variables "
  67.  
  68.    Private Shared lnk As New ShellLink()
  69.    Private Shared lnk_data As New WIN32_FIND_DATAW()
  70.  
  71.    Private Shared lnk_arguments As New StringBuilder(260)
  72.    Private Shared lnk_description As New StringBuilder(260)
  73.    Private Shared lnk_target As New StringBuilder(260)
  74.    Private Shared lnk_workingdir As New StringBuilder(260)
  75.    Private Shared lnk_iconpath As New StringBuilder(260)
  76.    Private Shared lnk_iconindex As Integer = -1
  77.    Private Shared lnk_hotkey As Short = -1
  78.    Private Shared lnk_windowstate As ShortcutWindowState = ShortcutWindowState.Normal
  79.  
  80. #End Region
  81.  
  82. #Region " API, Interfaces, Enumerations "
  83.  
  84.    <DllImport("shfolder.dll",
  85.    CharSet:=CharSet.Auto)>
  86.    Friend Shared Function SHGetFolderPath(ByVal hwndOwner As IntPtr,
  87.                                           ByVal nFolder As Integer,
  88.                                           ByVal hToken As IntPtr,
  89.                                           ByVal dwFlags As Integer,
  90.                                           ByVal lpszPath As StringBuilder
  91.    ) As Integer
  92.    End Function
  93.  
  94.    <Flags()>
  95.    Private Enum SLGP_FLAGS
  96.  
  97.        ''' <summary>
  98.        ''' Retrieves the standard short (8.3 format) file name.
  99.        ''' </summary>
  100.        SLGP_SHORTPATH = &H1
  101.  
  102.        ''' <summary>
  103.        ''' Retrieves the Universal Naming Convention (UNC) path name of the file.
  104.        ''' </summary>
  105.        SLGP_UNCPRIORITY = &H2
  106.  
  107.        ''' <summary>
  108.        ''' Retrieves the raw path name.
  109.        ''' A raw path is something that might not exist and may include environment variables that need to be expanded.
  110.        ''' </summary>
  111.        SLGP_RAWPATH = &H4
  112.  
  113.    End Enum
  114.  
  115.    <Flags()>
  116.    Private Enum SLR_FLAGS
  117.  
  118.        ''' <summary>
  119.        ''' Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
  120.        ''' the high-order word of fFlags can be set to a time-out value that specifies the
  121.        ''' maximum amount of time to be spent resolving the link. The function returns if the
  122.        ''' link cannot be resolved within the time-out duration. If the high-order word is set
  123.        ''' to zero, the time-out duration will be set to the default value of 3,000 milliseconds
  124.        ''' (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
  125.        ''' duration, in milliseconds.
  126.        ''' </summary>
  127.        SLR_NO_UI = &H1
  128.  
  129.        ''' <summary>
  130.        ''' If the link object has changed, update its path and list of identifiers.
  131.        ''' If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine,
  132.        ''' whether or not the link object has changed.
  133.        ''' </summary>
  134.        SLR_UPDATE = &H4
  135.  
  136.        ''' <summary>
  137.        ''' Do not update the link information
  138.        ''' </summary>
  139.        SLR_NOUPDATE = &H8
  140.  
  141.        ''' <summary>
  142.        ''' Do not execute the search heuristics
  143.        ''' </summary>
  144.        SLR_NOSEARCH = &H10
  145.  
  146.        ''' <summary>
  147.        ''' Do not use distributed link tracking
  148.        ''' </summary>
  149.        SLR_NOTRACK = &H20
  150.  
  151.        ''' <summary>
  152.        ''' Disable distributed link tracking.
  153.        ''' By default, distributed link tracking tracks removable media,
  154.        ''' across multiple devices based on the volume name.
  155.        ''' It also uses the Universal Naming Convention (UNC) path to track remote file systems,
  156.        ''' whose drive letter has changed.
  157.        ''' Setting SLR_NOLINKINFO disables both types of tracking.
  158.        ''' </summary>
  159.        SLR_NOLINKINFO = &H40
  160.  
  161.        ''' <summary>
  162.        ''' Call the Microsoft Windows Installer
  163.        ''' </summary>
  164.        SLR_INVOKE_MSI = &H80
  165.  
  166.    End Enum
  167.  
  168.    ''' <summary>
  169.    ''' Stores information about a shortcut file.
  170.    ''' </summary>
  171.    Public Class ShortcutInfo
  172.  
  173.        ''' <summary>
  174.        ''' Shortcut file full path.
  175.        ''' </summary>
  176.        Public Property ShortcutFile As String
  177.  
  178.        ''' <summary>
  179.        ''' Shortcut Comment/Description.
  180.        ''' </summary>
  181.        Public Property Description As String
  182.  
  183.        ''' <summary>
  184.        ''' Shortcut Target Arguments.
  185.        ''' </summary>
  186.        Public Property Arguments As String
  187.  
  188.        ''' <summary>
  189.        ''' Shortcut Target.
  190.        ''' </summary>
  191.        Public Property Target As String
  192.  
  193.        ''' <summary>
  194.        ''' Shortcut Working Directory.
  195.        ''' </summary>
  196.        Public Property WorkingDir As String
  197.  
  198.        ''' <summary>
  199.        ''' Shortcut Icon Location.
  200.        ''' </summary>
  201.        Public Property Icon As String
  202.  
  203.        ''' <summary>
  204.        ''' Shortcut Icon Index.
  205.        ''' </summary>
  206.        Public Property IconIndex As Integer
  207.  
  208.        ''' <summary>
  209.        ''' Shortcut Hotkey combination.
  210.        ''' Is represented as Hexadecimal.
  211.        ''' </summary>
  212.        Public Property Hotkey As Short
  213.  
  214.        ''' <summary>
  215.        ''' Shortcut Hotkey modifiers.
  216.        ''' </summary>
  217.        Public Property Hotkey_Modifier As HotkeyModifiers
  218.  
  219.        ''' <summary>
  220.        ''' Shortcut Hotkey Combination.
  221.        ''' </summary>
  222.        Public Property Hotkey_Key As Keys
  223.  
  224.        ''' <summary>
  225.        ''' Shortcut Window State.
  226.        ''' </summary>
  227.        Public Property WindowState As ShortcutWindowState
  228.  
  229.        ''' <summary>
  230.        ''' Indicates if the target is a file.
  231.        ''' </summary>
  232.        Public Property IsFile As Boolean
  233.  
  234.        ''' <summary>
  235.        ''' Indicates if the target is a directory.
  236.        ''' </summary>
  237.        Public Property IsDirectory As Boolean
  238.  
  239.        ''' <summary>
  240.        ''' Shortcut target drive letter.
  241.        ''' </summary>
  242.        Public Property DriveLetter As String
  243.  
  244.        ''' <summary>
  245.        ''' Shortcut target directory name.
  246.        ''' </summary>
  247.        Public Property DirectoryName As String
  248.  
  249.        ''' <summary>
  250.        ''' Shortcut target filename.
  251.        ''' (File extension is not included in name)
  252.        ''' </summary>
  253.        Public Property FileName As String
  254.  
  255.        ''' <summary>
  256.        ''' Shortcut target file extension.
  257.        ''' </summary>
  258.        Public Property FileExtension As String
  259.  
  260.    End Class
  261.  
  262.    ''' <summary>
  263.    ''' Hotkey modifiers for a shortcut file.
  264.    ''' </summary>
  265.    <FlagsAttribute()>
  266.    Public Enum HotkeyModifiers As Short
  267.  
  268.        ''' <summary>
  269.        ''' The SHIFT key.
  270.        ''' </summary>
  271.        SHIFT = 1
  272.  
  273.        ''' <summary>
  274.        ''' The CTRL key.
  275.        ''' </summary>
  276.        CONTROL = 2
  277.  
  278.        ''' <summary>
  279.        ''' The ALT key.
  280.        ''' </summary>
  281.        ALT = 4
  282.  
  283.        ''' <summary>
  284.        ''' None.
  285.        ''' Specifies any hotkey modificator.
  286.        ''' </summary>
  287.        NONE = 0
  288.  
  289.    End Enum
  290.  
  291.    ''' <summary>
  292.    ''' The Window States for a shortcut file.
  293.    ''' </summary>
  294.    Public Enum ShortcutWindowState As Integer
  295.  
  296.        ''' <summary>
  297.        ''' Shortcut Window is at normal state.
  298.        ''' </summary>
  299.        Normal = 1
  300.  
  301.        ''' <summary>
  302.        ''' Shortcut Window is Maximized.
  303.        ''' </summary>
  304.        Maximized = 3
  305.  
  306.        ''' <summary>
  307.        ''' Shortcut Window is Minimized.
  308.        ''' </summary>
  309.        Minimized = 7
  310.  
  311.    End Enum
  312.  
  313.    <StructLayout(LayoutKind.Sequential,
  314.    CharSet:=CharSet.Auto)>
  315.    Private Structure WIN32_FIND_DATAW
  316.        Public dwFileAttributes As UInteger
  317.        Public ftCreationTime As Long
  318.        Public ftLastAccessTime As Long
  319.        Public ftLastWriteTime As Long
  320.        Public nFileSizeHigh As UInteger
  321.        Public nFileSizeLow As UInteger
  322.        Public dwReserved0 As UInteger
  323.        Public dwReserved1 As UInteger
  324.        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)>
  325.        Public cFileName As String
  326.        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=14)>
  327.        Public cAlternateFileName As String
  328.    End Structure
  329.  
  330.    ''' <summary>
  331.    ''' The IShellLink interface allows Shell links to be created, modified, and resolved
  332.    ''' </summary>
  333.    <ComImport(),
  334.    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
  335.    Guid("000214F9-0000-0000-C000-000000000046")>
  336.    Private Interface IShellLinkW
  337.  
  338.        ''' <summary>
  339.        ''' Retrieves the path and file name of a Shell link object.
  340.        ''' </summary>
  341.        Sub GetPath(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  342.                    ByVal pszFile As StringBuilder,
  343.                    ByVal cchMaxPath As Integer,
  344.                    ByRef pfd As WIN32_FIND_DATAW,
  345.                    ByVal fFlags As SLGP_FLAGS)
  346.  
  347.        ''' <summary>
  348.        ''' Retrieves the list of item identifiers for a Shell link object.
  349.        ''' </summary>
  350.        Sub GetIDList(ByRef ppidl As IntPtr)
  351.  
  352.        ''' <summary>
  353.        ''' Sets the pointer to an item identifier list (PIDL) for a Shell link object.
  354.        ''' </summary>
  355.        Sub SetIDList(ByVal pidl As IntPtr)
  356.  
  357.        ''' <summary>
  358.        ''' Retrieves the description string for a Shell link object.
  359.        ''' </summary>
  360.        Sub GetDescription(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  361.                           ByVal pszName As StringBuilder,
  362.                           ByVal cchMaxName As Integer)
  363.  
  364.        ''' <summary>
  365.        ''' Sets the description for a Shell link object.
  366.        ''' The description can be any application-defined string.
  367.        ''' </summary>
  368.        Sub SetDescription(<MarshalAs(UnmanagedType.LPWStr)>
  369.                           ByVal pszName As String)
  370.  
  371.        ''' <summary>
  372.        ''' Retrieves the name of the working directory for a Shell link object.
  373.        ''' </summary>
  374.        Sub GetWorkingDirectory(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  375.                                ByVal pszDir As StringBuilder,
  376.                                ByVal cchMaxPath As Integer)
  377.  
  378.        ''' <summary>
  379.        ''' Sets the name of the working directory for a Shell link object.
  380.        ''' </summary>
  381.        Sub SetWorkingDirectory(<MarshalAs(UnmanagedType.LPWStr)>
  382.                                ByVal pszDir As String)
  383.  
  384.        ''' <summary>
  385.        ''' Retrieves the command-line arguments associated with a Shell link object.
  386.        ''' </summary>
  387.        Sub GetArguments(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  388.                         ByVal pszArgs As StringBuilder,
  389.                         ByVal cchMaxPath As Integer)
  390.  
  391.        ''' <summary>
  392.        ''' Sets the command-line arguments for a Shell link object.
  393.        ''' </summary>
  394.        Sub SetArguments(<MarshalAs(UnmanagedType.LPWStr)>
  395.                         ByVal pszArgs As String)
  396.  
  397.        ''' <summary>
  398.        ''' Retrieves the hot key for a Shell link object.
  399.        ''' </summary>
  400.        Sub GetHotkey(ByRef pwHotkey As Short)
  401.  
  402.        ''' <summary>
  403.        ''' Sets a hot key for a Shell link object.
  404.        ''' </summary>
  405.        Sub SetHotkey(ByVal wHotkey As Short)
  406.  
  407.        ''' <summary>
  408.        ''' Retrieves the show command for a Shell link object.
  409.        ''' </summary>
  410.        Sub GetShowCmd(ByRef piShowCmd As Integer)
  411.  
  412.        ''' <summary>
  413.        ''' Sets the show command for a Shell link object.
  414.        ''' The show command sets the initial show state of the window.
  415.        ''' </summary>
  416.        Sub SetShowCmd(ByVal iShowCmd As ShortcutWindowState)
  417.  
  418.        ''' <summary>
  419.        ''' Retrieves the location (path and index) of the icon for a Shell link object.
  420.        ''' </summary>
  421.        Sub GetIconLocation(<Out(), MarshalAs(UnmanagedType.LPWStr)>
  422.                            ByVal pszIconPath As StringBuilder,
  423.                            ByVal cchIconPath As Integer,
  424.                            ByRef piIcon As Integer)
  425.  
  426.        ''' <summary>
  427.        ''' Sets the location (path and index) of the icon for a Shell link object.
  428.        ''' </summary>
  429.        Sub SetIconLocation(<MarshalAs(UnmanagedType.LPWStr)>
  430.                            ByVal pszIconPath As String,
  431.                            ByVal iIcon As Integer)
  432.  
  433.        ''' <summary>
  434.        ''' Sets the relative path to the Shell link object.
  435.        ''' </summary>
  436.        Sub SetRelativePath(<MarshalAs(UnmanagedType.LPWStr)>
  437.                            ByVal pszPathRel As String,
  438.                            ByVal dwReserved As Integer)
  439.  
  440.        ''' <summary>
  441.        ''' Attempts to find the target of a Shell link,
  442.        ''' even if it has been moved or renamed.
  443.        ''' </summary>
  444.        Sub Resolve(ByVal hwnd As IntPtr,
  445.                    ByVal fFlags As SLR_FLAGS)
  446.  
  447.        ''' <summary>
  448.        ''' Sets the path and file name of a Shell link object
  449.        ''' </summary>
  450.        Sub SetPath(ByVal pszFile As String)
  451.  
  452.    End Interface
  453.  
  454.    <ComImport(), Guid("0000010c-0000-0000-c000-000000000046"),
  455.    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
  456.    Public Interface IPersist
  457.  
  458.        <PreserveSig()>
  459.        Sub GetClassID(ByRef pClassID As Guid)
  460.  
  461.    End Interface
  462.  
  463.    <ComImport(), Guid("0000010b-0000-0000-C000-000000000046"),
  464.    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
  465.    Public Interface IPersistFile
  466.        Inherits IPersist
  467.  
  468.        Shadows Sub GetClassID(ByRef pClassID As Guid)
  469.  
  470.        <PreserveSig()>
  471.        Function IsDirty() As Integer
  472.  
  473.        <PreserveSig()>
  474.        Sub Load(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  475.                 pszFileName As String,
  476.                 dwMode As UInteger)
  477.  
  478.        <PreserveSig()>
  479.        Sub Save(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  480.                 pszFileName As String,
  481.                 <[In](), MarshalAs(UnmanagedType.Bool)>
  482.                 fRemember As Boolean)
  483.  
  484.        <PreserveSig()>
  485.        Sub SaveCompleted(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  486.                          pszFileName As String)
  487.  
  488.        <PreserveSig()>
  489.        Sub GetCurFile(<[In](), MarshalAs(UnmanagedType.LPWStr)>
  490.                       ppszFileName As String)
  491.  
  492.    End Interface
  493.  
  494.    ' "CLSID_ShellLink" from "ShlGuid.h"
  495.    <ComImport(),
  496.    Guid("00021401-0000-0000-C000-000000000046")>
  497.    Public Class ShellLink
  498.    End Class
  499.  
  500. #End Region
  501.  
  502. #Region " Public Methods "
  503.  
  504.    ''' <summary>
  505.    ''' Resolves the target of a shortcut.
  506.    ''' If shortcut can't be resolved, an error message would be displayed.
  507.    ''' This is usefull when the target path of a shortcut file is changed from a driveletter for example,
  508.    ''' then the shortcut file need to be resolved before trying to retrieve the target path.
  509.    ''' </summary>
  510.    ''' <param name="ShortcutFile">
  511.    ''' The shortcut file to resolve.
  512.    ''' </param>
  513.    ''' <param name="hwnd">
  514.    ''' The new handle pointer that would be generated
  515.    ''' for the window which should display the error message (if any).
  516.    ''' </param>
  517.    Public Shared Sub Resolve_Ui(ShortcutFile As String, hwnd As IntPtr)
  518.        LoadShortcut(ShortcutFile)
  519.        DirectCast(lnk, IShellLinkW).Resolve(hwnd, SLR_FLAGS.SLR_UPDATE)
  520.    End Sub
  521.  
  522.    ''' <summary>
  523.    ''' Resolves the target of a shortcut.
  524.    ''' If shortcut can't be resolved, any error message would be displayed.
  525.    ''' This is usefull when the target path of a shortcut file is changed from a driveletter for example,
  526.    ''' then the shortcut file need to be resolved before trying to retrieve the target path.
  527.    ''' </summary>
  528.    ''' <param name="ShortcutFile">
  529.    ''' The shortcut file to resolve.
  530.    ''' </param>
  531.    Public Shared Sub Resolve_NoUi(ByVal ShortcutFile As String)
  532.        LoadShortcut(ShortcutFile)
  533.        DirectCast(lnk, IShellLinkW).Resolve(IntPtr.Zero, SLR_FLAGS.SLR_UPDATE Or SLR_FLAGS.SLR_NO_UI)
  534.    End Sub
  535.  
  536.    ''' <summary>
  537.    ''' Returns the description of a shortcut file.
  538.    ''' </summary>
  539.    ''' <param name="ShortcutFile">
  540.    ''' The shortcut file to retrieve the info.
  541.    ''' </param>
  542.    Public Shared Function Get_Description(ByVal ShortcutFile As String) As String
  543.        LoadShortcut(ShortcutFile)
  544.        lnk_description.Clear()
  545.        DirectCast(lnk, IShellLinkW).GetDescription(lnk_description, lnk_description.Capacity)
  546.        Return lnk_description.ToString()
  547.    End Function
  548.  
  549.    ''' <summary>
  550.    ''' Returns the Arguments of a shortcut file.
  551.    ''' </summary>
  552.    ''' <param name="ShortcutFile">
  553.    ''' The shortcut file to retrieve the info.
  554.    ''' </param>
  555.    Public Shared Function Get_Arguments(ByVal ShortcutFile As String) As String
  556.        LoadShortcut(ShortcutFile)
  557.        lnk_arguments.Clear()
  558.        DirectCast(lnk, IShellLinkW).GetArguments(lnk_arguments, lnk_arguments.Capacity)
  559.        Return lnk_arguments.ToString()
  560.    End Function
  561.  
  562.    ''' <summary>
  563.    ''' Returns the path and filename of a shortcut file.
  564.    ''' </summary>
  565.    ''' <param name="ShortcutFile">
  566.    ''' The shortcut file to retrieve the info.
  567.    ''' </param>
  568.    Public Shared Function Get_FullPath(ByVal ShortcutFile As String) As String
  569.        LoadShortcut(ShortcutFile)
  570.        lnk_target.Clear()
  571.        DirectCast(lnk, IShellLinkW).GetPath(lnk_target, lnk_target.Capacity, lnk_data, SLGP_FLAGS.SLGP_UNCPRIORITY)
  572.        Return lnk_target.ToString()
  573.    End Function
  574.  
  575.    ''' <summary>
  576.    ''' Returns the working directory of a shortcut file.
  577.    ''' </summary>
  578.    ''' <param name="ShortcutFile">
  579.    ''' The shortcut file to retrieve the info.
  580.    ''' </param>
  581.    Public Shared Function Get_WorkingDir(ByVal ShortcutFile As String) As String
  582.        LoadShortcut(ShortcutFile)
  583.        lnk_workingdir.Clear()
  584.        DirectCast(lnk, IShellLinkW).GetWorkingDirectory(lnk_workingdir, lnk_workingdir.Capacity)
  585.        Return lnk_workingdir.ToString()
  586.    End Function
  587.  
  588.    ''' <summary>
  589.    ''' Returns the Hotkey of a shortcut file.
  590.    ''' </summary>
  591.    ''' <param name="ShortcutFile">
  592.    ''' The shortcut file to retrieve the info.
  593.    ''' </param>
  594.    Public Shared Function Get_Hotkey(ByVal ShortcutFile As String) As Short
  595.        LoadShortcut(ShortcutFile)
  596.        lnk_hotkey = -1
  597.        DirectCast(lnk, IShellLinkW).GetHotkey(lnk_hotkey)
  598.        Return lnk_hotkey
  599.    End Function
  600.  
  601.    ''' <summary>
  602.    ''' Returns the Window State of a shortcut file.
  603.    ''' </summary>
  604.    ''' <param name="ShortcutFile">
  605.    ''' The shortcut file to retrieve the info.
  606.    ''' </param>
  607.    Public Shared Function Get_WindowStyle(ByVal ShortcutFile As String) As ShortcutWindowState
  608.        LoadShortcut(ShortcutFile)
  609.        DirectCast(lnk, IShellLinkW).GetShowCmd(lnk_windowstate)
  610.        Return lnk_windowstate
  611.    End Function
  612.  
  613.    ''' <summary>
  614.    ''' Returns the Icon location of a shortcut file.
  615.    ''' </summary>
  616.    ''' <param name="ShortcutFile">
  617.    ''' The shortcut file to retrieve the info.
  618.    ''' </param>
  619.    ''' <param name="IconIndex">
  620.    ''' Optional Integer type variable to store the IconIndex.
  621.    ''' </param>
  622.    Public Shared Function Get_IconLocation(ByVal ShortcutFile As String,
  623.                                            Optional ByRef IconIndex As Integer = 0) As String
  624.        LoadShortcut(ShortcutFile)
  625.        lnk_iconpath.Clear()
  626.        DirectCast(lnk, IShellLinkW).GetIconLocation(lnk_iconpath, lnk_iconpath.Capacity, IconIndex)
  627.        Return lnk_iconpath.ToString()
  628.    End Function
  629.  
  630.    ''' <summary>
  631.    ''' Retrieves all the information about a shortcut file.
  632.    ''' </summary>
  633.    ''' <param name="ShortcutFile">
  634.    ''' The shortcut file to retrieve the info.
  635.    ''' </param>
  636.    Public Shared Function GetInfo(ByVal ShortcutFile As String) As ShortcutInfo
  637.  
  638.        ' Load Shortcut
  639.        LoadShortcut(ShortcutFile)
  640.  
  641.        ' Clean objects
  642.        lnk_description.Clear()
  643.        lnk_arguments.Clear()
  644.        lnk_target.Clear()
  645.        lnk_workingdir.Clear()
  646.        lnk_iconpath.Clear()
  647.        lnk_hotkey = -1
  648.        lnk_iconindex = -1
  649.  
  650.        ' Retrieve Info
  651.        DirectCast(lnk, IShellLinkW).GetDescription(lnk_description, lnk_description.Capacity)
  652.        DirectCast(lnk, IShellLinkW).GetArguments(lnk_arguments, lnk_arguments.Capacity)
  653.        DirectCast(lnk, IShellLinkW).GetPath(lnk_target, lnk_target.Capacity, lnk_data, SLGP_FLAGS.SLGP_UNCPRIORITY)
  654.        DirectCast(lnk, IShellLinkW).GetWorkingDirectory(lnk_workingdir, lnk_workingdir.Capacity)
  655.        DirectCast(lnk, IShellLinkW).GetIconLocation(lnk_iconpath, lnk_iconpath.Capacity, lnk_iconindex)
  656.        DirectCast(lnk, IShellLinkW).GetHotkey(lnk_hotkey)
  657.        DirectCast(lnk, IShellLinkW).GetShowCmd(lnk_windowstate)
  658.  
  659.        ' Return Info
  660.        Return New ShortcutInfo With {
  661.            .ShortcutFile = ShortcutFile,
  662.            .Description = lnk_description.ToString,
  663.            .Arguments = lnk_arguments.ToString,
  664.            .Target = lnk_target.ToString,
  665.            .Icon = lnk_iconpath.ToString,
  666.            .IconIndex = lnk_iconindex,
  667.            .WorkingDir = lnk_workingdir.ToString,
  668.            .Hotkey = Hex(lnk_hotkey),
  669.            .Hotkey_Modifier = [Enum].Parse(GetType(HotkeyModifiers), GetHiByte(lnk_hotkey)),
  670.            .Hotkey_Key = [Enum].Parse(GetType(Keys), GetLoByte(lnk_hotkey)),
  671.            .WindowState = lnk_windowstate,
  672.            .IsFile = File.Exists(lnk_target.ToString),
  673.            .IsDirectory = Directory.Exists(lnk_target.ToString),
  674.            .DriveLetter = lnk_target.ToString.Substring(0, 1),
  675.            .DirectoryName = lnk_target.ToString.Substring(0, lnk_target.ToString.LastIndexOf("\")),
  676.            .FileName = lnk_target.ToString.Split("\").LastOrDefault.Split(".").FirstOrDefault,
  677.            .FileExtension = lnk_target.ToString.Split(".").LastOrDefault
  678.        }
  679.  
  680.    End Function
  681.  
  682.    ''' <summary>
  683.    ''' Creates a shortcut file.
  684.    ''' </summary>
  685.    ''' <param name="FilePath">
  686.    ''' The filepath to create the shortcut.
  687.    ''' </param>
  688.    ''' <param name="Target">
  689.    ''' The target file or directory.
  690.    ''' </param>
  691.    ''' <param name="WorkingDirectory">
  692.    ''' The working directory os the shortcut.
  693.    ''' </param>
  694.    ''' <param name="Description">
  695.    ''' The shortcut description.
  696.    ''' </param>
  697.    ''' <param name="Arguments">
  698.    ''' The target file arguments.
  699.    ''' This value only should be set when target is an executable file.
  700.    ''' </param>
  701.    ''' <param name="Icon">
  702.    ''' The icon location of the shortcut.
  703.    ''' </param>
  704.    ''' <param name="IconIndex">
  705.    ''' The icon index of the icon file.
  706.    ''' </param>
  707.    ''' <param name="HotKey_Modifier">
  708.    ''' The hotkey modifier(s) which should be used for the hotkey combination.
  709.    ''' <paramref name="HotkeyModifiers"/> can be one or more modifiers.
  710.    ''' </param>
  711.    ''' <param name="HotKey_Key">
  712.    ''' The key used in combination with the <paramref name="HotkeyModifiers"/> for hotkey combination.
  713.    ''' </param>
  714.    ''' <param name="WindowState">
  715.    ''' The Window state for the target.
  716.    ''' </param>
  717.    Public Shared Sub Create(ByVal FilePath As String,
  718.                             ByVal Target As String,
  719.                             Optional ByVal WorkingDirectory As String = Nothing,
  720.                             Optional ByVal Description As String = Nothing,
  721.                             Optional ByVal Arguments As String = Nothing,
  722.                             Optional ByVal Icon As String = Nothing,
  723.                             Optional ByVal IconIndex As Integer = Nothing,
  724.                             Optional ByVal HotKey_Modifier As HotkeyModifiers = Nothing,
  725.                             Optional ByVal HotKey_Key As Keys = Nothing,
  726.                             Optional ByVal WindowState As ShortcutWindowState = ShortcutWindowState.Normal)
  727.  
  728.        LoadShortcut(FilePath)
  729.  
  730.        DirectCast(lnk, IShellLinkW).SetPath(Target)
  731.  
  732.        DirectCast(lnk, IShellLinkW).SetWorkingDirectory(If(WorkingDirectory IsNot Nothing,
  733.                                                            WorkingDirectory,
  734.                                                            Path.GetDirectoryName(Target)))
  735.  
  736.        DirectCast(lnk, IShellLinkW).SetDescription(Description)
  737.        DirectCast(lnk, IShellLinkW).SetArguments(Arguments)
  738.        DirectCast(lnk, IShellLinkW).SetIconLocation(Icon, IconIndex)
  739.  
  740.        DirectCast(lnk, IShellLinkW).SetHotkey(If(HotKey_Modifier + HotKey_Key <> 0,
  741.                                                  Convert.ToInt32(CInt(HotKey_Modifier & Hex(HotKey_Key)), 16),
  742.                                                  Nothing))
  743.  
  744.        DirectCast(lnk, IShellLinkW).SetShowCmd(WindowState)
  745.  
  746.        DirectCast(lnk, IPersistFile).Save(FilePath, True)
  747.        DirectCast(lnk, IPersistFile).SaveCompleted(FilePath)
  748.  
  749.    End Sub
  750.  
  751. #End Region
  752.  
  753. #Region " Private Methods "
  754.  
  755.    ''' <summary>
  756.    ''' Loads the shortcut object to retrieve information.
  757.    ''' </summary>
  758.    ''' <param name="ShortcutFile">
  759.    ''' The shortcut file to retrieve the info.
  760.    ''' </param>
  761.    Private Shared Sub LoadShortcut(ByVal ShortcutFile As String)
  762.        DirectCast(lnk, IPersistFile).Load(ShortcutFile, 0)
  763.    End Sub
  764.  
  765.    ''' <summary>
  766.    ''' Gets the low order byte of a number.
  767.    ''' </summary>
  768.    Private Shared Function GetLoByte(ByVal Intg As Integer) As Integer
  769.        Return Intg And &HFF&
  770.    End Function
  771.  
  772.    ''' <summary>
  773.    ''' Gets the high order byte of a number.
  774.    ''' </summary>
  775.    Private Shared Function GetHiByte(ByVal Intg As Integer) As Integer
  776.        Return (Intg And &HFF00&) / 256
  777.    End Function
  778.  
  779. #End Region
  780.  
  781. End Class
  782.  
  783. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #344 en: 20 Noviembre 2013, 14:32 pm »

Otro ayudante más, en esta ocasión es para la aplicación FFMPEG,
no le añadí ningún método para convertir video (pero si uno para el audio) ya que no necesito convertir la pista de video, pero el código es facil de extender, solo hay que seguir el ejemplo del audio.

PD: Existen varios wrappers de FFMPEG para .NET, pero... todos obsoletos, en C#, y no he visto ninguno que tenga un triste evento al que subscribirse.





Código
  1.  
  2.  
  3. ' [ FFMPEG Helper ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Instructions:
  8. '
  9. ' 1. Add the "FFMPEG.exe" into the project
  10.  
  11.  
  12. #Region " FFMPEG Helper "
  13.  
  14. #Region " Usage Examples "
  15.  
  16. 'Public Class Form1
  17.  
  18. '    Private WithEvents _FFMPEG As New FFMPEG With
  19. '    {.FFMPEG_location = "C:\windows\system32\ffmpeg.exe", .CheckFileExist = False}
  20.  
  21. '    Private Shadows Sub Shown() Handles MyBase.Shown
  22.  
  23. '        ' Checks if FFMPEG executable is avaliable.
  24. '        MsgBox(_FFMPEG.Is_Avaliable())
  25.  
  26. '        ' Checks if a video has metadata
  27. '        MsgBox(_FFMPEG.HasMetadata("C:\Video.mkv"))
  28.  
  29. '        ' Remove metadata from video
  30. '        _FFMPEG.RemoveMetadata("C:\Input.mkv", "C:\Output.mkv", True, 4)
  31.  
  32. '        ' reCompress the audio track of a video
  33. '        _FFMPEG.Recompress_AudioTrack("C:\Input.mkv", "C:\Output.mkv", True,
  34. '                                      FFMPEG.AudioCodec.libmp3lame, FFMPEG.AudioBitRate.kbps_128, 4)
  35.  
  36. '    End Sub
  37.  
  38. '    ' FFMPEG [Started]
  39. '    Private Sub FFMPEG_Started(ByVal sender As Process, ByVal e As FFMPEG.StartedEventArgs) _
  40. '    Handles _FFMPEG.Started
  41.  
  42. '        ProgressBar1.Value = ProgressBar1.Minimum
  43.  
  44. '        Dim sb As New System.Text.StringBuilder
  45.  
  46. '        sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString))
  47. '        sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  48. '        sb.AppendLine(String.Format("FFMPEG process PID is: ""{0}""", CStr(sender.Id)))
  49.  
  50. '        MessageBox.Show(sb.ToString, "FFMPEG", MessageBoxButtons.OK, MessageBoxIcon.Information)
  51.  
  52. '    End Sub
  53.  
  54. '    ' FFMPEG [Exited]
  55. '    Private Sub FFMPEG_Exited(ByVal sender As Process, ByVal e As FFMPEG.ExitedEventArgs) _
  56. '    Handles _FFMPEG.Exited
  57.  
  58. '        Dim sb As New System.Text.StringBuilder
  59.  
  60. '        sb.AppendLine(String.Format("Finished an ""{0}"" operation", e.Operation.ToString))
  61. '        sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  62. '        sb.AppendLine(String.Format("FFMPEG process PID is: {0}", CStr(sender.Id)))
  63.  
  64. '        If e.Errors.Count <> 0 Then
  65. '            sb.AppendLine(String.Format("Errors during operation: {0}", String.Join(Environment.NewLine, e.Errors)))
  66. '        End If
  67.  
  68. '        MessageBox.Show(sb.ToString, "FFMPEG", MessageBoxButtons.OK, MessageBoxIcon.Information)
  69.  
  70. '    End Sub
  71.  
  72. '    ' FFMPEG [Progress]
  73. '    Private Sub FFMPEG_Progress(sender As Process, e As FFMPEG.ProgressEventArgs) _
  74. '    Handles _FFMPEG.Progress
  75.  
  76. '        ProgressBar1.Value = e.Percent
  77.  
  78. '        Label1.Text = "Percent Done: " & CStr(e.Percent) & "%"
  79. '        Label2.Text = "Video Duration: " & e.VideoDuration.ToString("hh\:mm\:ss")
  80. '        Label3.Text = "Written Duration: " & e.Time.ToString("hh\:mm\:ss")
  81. '        Label4.Text = "Written Data: " & (e.WrittenBytes / 1024L * 1024L).ToString("n1") & "MB"
  82.  
  83. '    End Sub
  84.  
  85. 'End Class
  86.  
  87. #End Region
  88.  
  89. #Region " CommandLine Parameter legend "
  90.  
  91. '-y        | Overwrite output files without asking.
  92. '-n        | Do not overwrite output files, and exit immediately if a specified output file already exists.
  93. '-threads: |  Specify the cpu threads to use.
  94. '-nostdin  | Disable interaction on standard input.
  95. '-vcodec   | Set the video codec.
  96. '-acodec   | Set the audio codec.
  97. '-vn       | Disable video recording.
  98. '-an       | Disable audio recording.
  99.  
  100. ' -c copy -map_metadata -1
  101. ' Don't add metadata.
  102.  
  103. #End Region
  104.  
  105. Public Class FFMPEG : Implements IDisposable
  106.  
  107. #Region " Variables, Properties, Enumerations "
  108.  
  109.    ''' <summary>
  110.    ''' Gets or sets FFMPEG.exe executable path.
  111.    ''' </summary>
  112.    Public Property FFMPEG_location As String = ".\FFMPEG.exe"
  113.  
  114.    ''' <summary>
  115.    ''' Unique temp file to write FFMPEG output.
  116.    ''' </summary>
  117.    Private ReadOnly TempFile As String = IO.Path.GetTempFileName
  118.  
  119.    ''' <summary>
  120.    ''' Indicates if should check that the file exist before realize an operation.
  121.    ''' If True, an exception would be launched if file does not exist.
  122.    ''' </summary>
  123.    Public Property CheckFileExist As Boolean = False
  124.  
  125.    ''' <summary>
  126.    ''' Stores the next FFMEP process output line.
  127.    ''' </summary>
  128.    Private OutputLine As String = Nothing
  129.  
  130.    ''' <summary>
  131.    ''' Stores the Video Duration.
  132.    ''' </summary>
  133.    Private VideoDuration As TimeSpan = Nothing
  134.  
  135.    ''' <summary>
  136.    ''' Stores the processed video time.
  137.    ''' </summary>
  138.    Private Time As TimeSpan = Nothing
  139.  
  140.    ''' <summary>
  141.    ''' Stores the conversion errors (if any).
  142.    ''' </summary>
  143.    Private Errors As New List(Of String)
  144.  
  145.    ''' <summary>
  146.    ''' Stores the StartedEventArgs Arguments.
  147.    ''' </summary>
  148.    Private StartedArgs As New StartedEventArgs
  149.  
  150.    ''' <summary>
  151.    ''' Stores the ExitedEventArgs Arguments.
  152.    ''' </summary>
  153.    Private ExitedArgs As New ExitedEventArgs
  154.  
  155.    ''' <summary>
  156.    ''' Stores the ProgressEventArgs Arguments.
  157.    ''' </summary>
  158.    Private ProgressArgs As New ProgressEventArgs
  159.  
  160.    ''' <summary>
  161.    ''' FFMPEG kind Of Operation.
  162.    ''' </summary>
  163.    Public Enum Operation As Short
  164.        Check_Metadata = 0
  165.        Remove_Metadata = 1
  166.        Recompress_AudioTrack = 2
  167.    End Enum
  168.  
  169.    ''' <summary>
  170.    ''' FFMPEG Process.
  171.    ''' </summary>
  172.    Private p As Process =
  173.        New Process With {.StartInfo =
  174.            New ProcessStartInfo With {
  175.                .CreateNoWindow = True, _
  176.                .UseShellExecute = False, _
  177.                .RedirectStandardError = True, _
  178.                .RedirectStandardOutput = True, _
  179.                .StandardErrorEncoding = System.Text.Encoding.Default, _
  180.                .StandardOutputEncoding = System.Text.Encoding.Default
  181.           }
  182.        }
  183.  
  184.    ''' <summary>
  185.    ''' Audio Codec use for the conversion.
  186.    ''' </summary>
  187.    Public Enum AudioCodec
  188.  
  189.        ''' <summary>
  190.        ''' MP3 Audio.
  191.        ''' </summary>
  192.        libmp3lame
  193.  
  194.        ''' <summary>
  195.        ''' Windows Media Audio.
  196.        ''' </summary>
  197.        wmav2
  198.  
  199.    End Enum
  200.  
  201.    ''' <summary>
  202.    ''' BitRate used for the audio compression.
  203.    ''' </summary>
  204.    Public Enum AudioBitRate As Integer
  205.        kbps_24 = 24
  206.        kbps_32 = 32
  207.        kbps_40 = 40
  208.        kbps_48 = 48
  209.        kbps_56 = 56
  210.        kbps_64 = 64
  211.        kbps_80 = 80
  212.        kbps_96 = 96
  213.        kbps_112 = 112
  214.        kbps_128 = 128
  215.        kbps_144 = 144
  216.        kbps_160 = 160
  217.        kbps_192 = 192
  218.        kbps_224 = 224
  219.        kbps_256 = 256
  220.        kbps_320 = 320
  221.    End Enum
  222.  
  223. #End Region
  224.  
  225. #Region " Events "
  226.  
  227.    ''' <summary>
  228.    ''' Event raised when FFMPEG operation progress changes.
  229.    ''' </summary>
  230.    Public Event Progress As EventHandler(Of ProgressEventArgs)
  231.    Public Class ProgressEventArgs : Inherits EventArgs
  232.  
  233.        ''' <summary>
  234.        ''' The FFMPEG operation percent done.
  235.        ''' </summary>
  236.        Public Property Percent As Integer
  237.  
  238.        ''' <summary>
  239.        ''' The Input Video Duration.
  240.        ''' </summary>
  241.        Public Property VideoDuration As TimeSpan
  242.  
  243.        ''' <summary>
  244.        ''' The processed video time.
  245.        ''' </summary>
  246.        Public Property Time As TimeSpan
  247.  
  248.        ''' <summary>
  249.        ''' The total amount of written bytes.
  250.        ''' </summary>
  251.        Public Property WrittenBytes As Double
  252.  
  253.    End Class
  254.  
  255.    ''' <summary>
  256.    ''' Event raised when FFMPEG process has started.
  257.    ''' </summary>
  258.    Public Event Started As EventHandler(Of StartedEventArgs)
  259.    Public Class StartedEventArgs : Inherits EventArgs
  260.  
  261.        ''' <summary>
  262.        ''' Gets the file that was passed as argument to the process.
  263.        ''' </summary>
  264.        Public Property File As String
  265.  
  266.        ''' <summary>
  267.        ''' Gets the type of operation to realize.
  268.        ''' </summary>
  269.        Public Property Operation As Operation
  270.  
  271.    End Class
  272.  
  273.    ''' <summary>
  274.    ''' Event raised when FFMPEG process has exited.
  275.    ''' </summary>
  276.    Public Event Exited As EventHandler(Of ExitedEventArgs)
  277.    Public Class ExitedEventArgs : Inherits EventArgs
  278.  
  279.        ''' <summary>
  280.        ''' Gets the file that was passed as argument to the process.
  281.        ''' </summary>
  282.        Public Property File As String
  283.  
  284.        ''' <summary>
  285.        ''' Gets the type of operation to realize.
  286.        ''' </summary>
  287.        Public Property Operation As Operation
  288.  
  289.        ''' <summary>
  290.        ''' Gets an error message of the realized operation (if any).
  291.        ''' </summary>
  292.        Public Property Errors As List(Of String)
  293.  
  294.    End Class
  295.  
  296. #End Region
  297.  
  298. #Region " Public Methods "
  299.  
  300.    ''' <summary>
  301.    ''' Checks if FFMPEG process is avaliable.
  302.    ''' </summary>
  303.    Public Function Is_Avaliable() As Boolean
  304.        Return IO.File.Exists(Me.FFMPEG_location)
  305.    End Function
  306.  
  307.    ''' <summary>
  308.    ''' Checks if a video file contains metadata fields.
  309.    ''' </summary>
  310.    Public Function HasMetadata(ByVal VideoFile As String) As Boolean
  311.  
  312.        DisposedCheck()
  313.  
  314.        p.StartInfo.Arguments =
  315.          String.Format("-y -i ""{0}"" -f ffmetadata ""{1}""",
  316.                        VideoFile,
  317.                        TempFile)
  318.  
  319.        Run_FFMPEG(VideoFile, Operation.Check_Metadata)
  320.  
  321.        Return IO.File.ReadAllText(TempFile).Replace(";FFMETADATA1", "").Trim.Length <> 0
  322.  
  323.    End Function
  324.  
  325.    ''' <summary>
  326.    ''' Removes the metadata tags from a video file.
  327.    ''' </summary>
  328.    Public Sub RemoveMetadata(ByVal VideoFile As String,
  329.                              ByVal OutputFile As String,
  330.                              ByVal OverWrite As Boolean,
  331.                              Optional ByVal Threads As Integer = 1)
  332.  
  333.        DisposedCheck()
  334.  
  335.        p.StartInfo.Arguments =
  336.          String.Format("-nostdin -threads {2} {3} -i ""{0}"" -c copy -map_metadata -1 ""{1}""",
  337.                        VideoFile,
  338.                        OutputFile,
  339.                        Threads,
  340.                        If(OverWrite, "-y", "-n"))
  341.  
  342.        Run_FFMPEG(VideoFile, Operation.Remove_Metadata)
  343.  
  344.    End Sub
  345.  
  346.    ''' <summary>
  347.    ''' ReCompress the audio track of a video file.
  348.    ''' </summary>
  349.    Public Sub Recompress_AudioTrack(ByVal VideoFile As String,
  350.                                     ByVal OutputFile As String,
  351.                                     ByVal OverWrite As Boolean,
  352.                                     ByVal AudioCodec As AudioCodec,
  353.                                     ByVal Bitrate As AudioBitRate,
  354.                                     Optional ByVal CopyMetadata As Boolean = False,
  355.                                     Optional ByVal Threads As Integer = 1)
  356.  
  357.        DisposedCheck()
  358.  
  359.        p.StartInfo.Arguments =
  360.          String.Format("-nostdin -threads {2} {3} -i ""{0}"" {6} -vcodec copy -acodec {4} -ab {5} ""{1}""",
  361.                        VideoFile,
  362.                        OutputFile,
  363.                        Threads,
  364.                        If(OverWrite, "-y", "-n"),
  365.                        AudioCodec.ToString,
  366.                        CStr(Bitrate) & "k",
  367.                        If(CopyMetadata, "", "-c copy -map_metadata -1"))
  368.  
  369.        Run_FFMPEG(VideoFile, Operation.Recompress_AudioTrack)
  370.  
  371.    End Sub
  372.  
  373. #End Region
  374.  
  375. #Region " Run Method "
  376.  
  377.    ''' <summary>
  378.    ''' Runs a specific operation of FFMPEG.
  379.    ''' </summary>
  380.    Private Sub Run_FFMPEG(ByVal file As String,
  381.                           ByVal Operation As Operation)
  382.  
  383.        If Me.CheckFileExist Then
  384.            FileExist(file)
  385.        End If
  386.  
  387.        VideoDuration = Nothing
  388.        Errors.Clear()
  389.  
  390.        p.StartInfo.FileName = Me.FFMPEG_location
  391.        p.Start()
  392.  
  393.        With StartedArgs
  394.            .File = file
  395.            .Operation = Operation
  396.        End With
  397.  
  398.        RaiseEvent Started(p, StartedArgs)
  399.  
  400.        While Not p.StandardError.EndOfStream
  401.  
  402.            ' Parse the Input Video Duration to calculate the percentage.
  403.            Do Until VideoDuration.TotalMilliseconds > 0
  404.  
  405.                OutputLine = p.StandardError.ReadLine.ToLower
  406.  
  407.                If OutputLine.Contains("duration") Then
  408.  
  409.                    Try
  410.                        VideoDuration = TimeSpan.Parse(OutputLine.Replace("duration:", "").
  411.                                                                  Split(",").FirstOrDefault)
  412.                    Catch ex As FormatException
  413.                        VideoDuration = TimeSpan.Parse("24:00:00") ' 00:00:00
  414.                    End Try
  415.  
  416.                End If
  417.            Loop
  418.  
  419.            ' Parse the percentage and other values.
  420.            OutputLine = p.StandardError.ReadLine.ToLower
  421.  
  422.            If OutputLine.StartsWith("frame=") Then
  423.  
  424.                Time = TimeSpan.Parse(OutputLine.Split("=")(5).Split.First)
  425.  
  426.                With ProgressArgs
  427.                    .VideoDuration = VideoDuration
  428.                    .Time = Time
  429.                    .Percent = (Time.TotalSeconds / VideoDuration.TotalSeconds) * 100
  430.                    .WrittenBytes = CDbl(OutputLine.Split("=")(4).Trim.Split.First.Replace("kb", "")) / 1024
  431.                End With
  432.  
  433.                RaiseEvent Progress(p, ProgressArgs)
  434.  
  435.            ElseIf (OutputLine.Contains("error") OrElse OutputLine.Contains("warning")) Then
  436.                Errors.Add(OutputLine)
  437. #If DEBUG Then
  438.                ' MsgBox("[DEBUG] FFMPEG Error: " & OutputLine)
  439. #End If
  440.            End If
  441.  
  442.        End While
  443.  
  444.        With ExitedArgs
  445.            .File = file
  446.            .Operation = Operation
  447.            .Errors = Errors
  448.        End With
  449.  
  450.        RaiseEvent Exited(p, ExitedArgs)
  451.  
  452.        ' FFMPEG.Close()
  453.  
  454.    End Sub
  455.  
  456. #End Region
  457.  
  458. #Region " Miscellaneous Methods "
  459.  
  460.    ''' <summary>
  461.    ''' Checks if a file exists.
  462.    ''' </summary>
  463.    Private Sub FileExist(ByVal File As String)
  464.  
  465.        If Not IO.File.Exists(File) Then
  466.            ' Throw New Exception("File doesn't exist: " & File)
  467.            MessageBox.Show("File doesn't exist: " & File, "FFMPEG", MessageBoxButtons.OK, MessageBoxIcon.Error)
  468.        End If
  469.  
  470.    End Sub
  471.  
  472. #End Region
  473.  
  474. #Region " IDisposable "
  475.  
  476.    ''' <summary>
  477.    ''' To detect redundant calls when disposing.
  478.    ''' </summary>
  479.    Private IsDisposed As Boolean = False
  480.  
  481.    ''' <summary>
  482.    ''' Prevents calls to methods after disposing.
  483.    ''' </summary>
  484.    Private Sub DisposedCheck()
  485.        If Me.IsDisposed Then
  486.            Throw New ObjectDisposedException(Me.GetType().FullName)
  487.        End If
  488.    End Sub
  489.  
  490.    ''' <summary>
  491.    ''' Disposes the objects generated by this instance.
  492.    ''' </summary>
  493.    Public Sub Dispose() Implements IDisposable.Dispose
  494.        Dispose(True)
  495.        GC.SuppressFinalize(Me)
  496.    End Sub
  497.  
  498.    ' IDisposable
  499.    Protected Overridable Sub Dispose(IsDisposing As Boolean)
  500.  
  501.        If Not Me.IsDisposed Then
  502.  
  503.            If IsDisposing Then
  504.                p.Dispose()
  505.            End If
  506.  
  507.        End If
  508.  
  509.        Me.IsDisposed = True
  510.  
  511.    End Sub
  512.  
  513. #End Region
  514.  
  515. End Class
  516.  
  517. #End Region


Un ejemplo de uso:

Código
  1. Public Class Form1
  2.  
  3.    Private WithEvents _FFMPEG As New FFMPEG With
  4.    {.FFMPEG_location = "C:\windows\system32\ffmpeg.exe", .CheckFileExist = False}
  5.  
  6.    Private Shadows Sub Shown() Handles MyBase.Shown
  7.  
  8.        ' Checks if FFMPEG executable is avaliable.
  9.        MsgBox(_FFMPEG.Is_Avaliable())
  10.  
  11.        ' Checks if a video has metadata
  12.        MsgBox(_FFMPEG.HasMetadata("C:\Video.mkv"))
  13.  
  14.        ' Remove metadata from video
  15.        _FFMPEG.RemoveMetadata("C:\Input.mkv", "C:\Output.mkv", True, 4)
  16.  
  17.        ' reCompress the audio track of a video
  18.        _FFMPEG.Recompress_AudioTrack("C:\Input.mkv", "C:\Output.mkv", True,
  19.                                      FFMPEG.AudioCodec.libmp3lame, FFMPEG.AudioBitRate.kbps_128, 4)
  20.  
  21.    End Sub
  22.  
  23.    ' FFMPEG [Started]
  24.    Private Sub FFMPEG_Started(ByVal sender As Process, ByVal e As FFMPEG.StartedEventArgs) _
  25.    Handles _FFMPEG.Started
  26.  
  27.        ProgressBar1.Value = ProgressBar1.Minimum
  28.  
  29.        Dim sb As New System.Text.StringBuilder
  30.  
  31.        sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString))
  32.        sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  33.        sb.AppendLine(String.Format("FFMPEG process PID is: ""{0}""", CStr(sender.Id)))
  34.  
  35.        MessageBox.Show(sb.ToString, "FFMPEG", MessageBoxButtons.OK, MessageBoxIcon.Information)
  36.  
  37.    End Sub
  38.  
  39.    ' FFMPEG [Exited]
  40.    Private Sub FFMPEG_Exited(ByVal sender As Process, ByVal e As FFMPEG.ExitedEventArgs) _
  41.    Handles _FFMPEG.Exited
  42.  
  43.        Dim sb As New System.Text.StringBuilder
  44.  
  45.        sb.AppendLine(String.Format("Finished an ""{0}"" operation", e.Operation.ToString))
  46.        sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
  47.        sb.AppendLine(String.Format("FFMPEG process PID is: {0}", CStr(sender.Id)))
  48.  
  49.        If e.Errors.Count <> 0 Then
  50.            sb.AppendLine(String.Format("Errors during operation: {0}", String.Join(Environment.NewLine, e.Errors)))
  51.        End If
  52.  
  53.        MessageBox.Show(sb.ToString, "FFMPEG", MessageBoxButtons.OK, MessageBoxIcon.Information)
  54.  
  55.    End Sub
  56.  
  57.    ' FFMPEG [Progress]
  58.    Private Sub FFMPEG_Progress(sender As Process, e As FFMPEG.ProgressEventArgs) _
  59.    Handles _FFMPEG.Progress
  60.  
  61.        ProgressBar1.Value = e.Percent
  62.  
  63.        Label1.Text = "Percent Done: " & CStr(e.Percent) & "%"
  64.        Label2.Text = "Video Duration: " & e.VideoDuration.ToString("hh\:mm\:ss")
  65.        Label3.Text = "Written Duration: " & e.Time.ToString("hh\:mm\:ss")
  66.        Label4.Text = "Written Data: " & (e.WrittenBytes / 1024L * 1024L).ToString("n1") & "MB"
  67.  
  68.    End Sub
  69.  
  70. End Class
« Última modificación: 20 Noviembre 2013, 14:48 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #345 en: 21 Noviembre 2013, 16:10 pm »

Desactivar la redimensión (resize) para ciertos lados del Form (izquierda, derecha, arriba, abajo, o esquinas...)

Código
  1. #Region " Form Resize Disabler "
  2.  
  3.    ' [ Form Resize Disabler ]
  4.    '
  5.    ' Examples:
  6.    ' Me.EnableResizeBottom = False
  7.    ' Me.EnableResizeTop = False
  8.  
  9.    Public Property EnableResizeTop As Boolean = True
  10.    Public Property EnableResizeLeft As Boolean = True
  11.    Public Property EnableResizeRight As Boolean = True
  12.    Public Property EnableResizeBottom As Boolean = True
  13.    Public Property EnableResizeTopLeft As Boolean = True
  14.    Public Property EnableResizeTopRight As Boolean = True
  15.    Public Property EnableResizeBottomLeft As Boolean = True
  16.    Public Property EnableResizeBottomRight As Boolean = True
  17.  
  18.    Private Enum NCHitTest As Integer
  19.        Transparent = -1
  20.        Nowhere = 0
  21.        Client = 1
  22.        Caption = 2
  23.        Left = 10
  24.        Right = 11
  25.        Top = 12
  26.        TopLeft = 13
  27.        TopRight = 14
  28.        Bottom = 15
  29.        BottomLeft = 16
  30.        BottomRight = 17
  31.        Border = 18
  32.    End Enum
  33.  
  34.    Protected Overrides Sub WndProc(ByRef m As Message)
  35.  
  36.        MyBase.WndProc(m)
  37.  
  38.        Select Case m.Msg
  39.  
  40.            Case &H84 ' WM_NCHITTEST
  41.  
  42.                Select Case CType(m.Result, NCHitTest)
  43.  
  44.                    Case NCHitTest.Top
  45.                        If Not Me.EnableResizeTop Then m.Result = New IntPtr(NCHitTest.Caption)
  46.  
  47.                    Case NCHitTest.Left
  48.                        If Not Me.EnableResizeLeft Then m.Result = New IntPtr(NCHitTest.Caption)
  49.  
  50.                    Case NCHitTest.Right
  51.                        If Not Me.EnableResizeRight Then m.Result = New IntPtr(NCHitTest.Caption)
  52.  
  53.                    Case NCHitTest.Bottom
  54.                        If Not Me.EnableResizeBottom Then m.Result = New IntPtr(NCHitTest.Caption)
  55.  
  56.                    Case NCHitTest.TopLeft
  57.                        If Not Me.EnableResizeTopLeft Then m.Result = New IntPtr(NCHitTest.Caption)
  58.  
  59.                    Case NCHitTest.TopRight
  60.                        If Not Me.EnableResizeTopRight Then m.Result = New IntPtr(NCHitTest.Caption)
  61.  
  62.                    Case NCHitTest.BottomLeft
  63.                        If Not Me.EnableResizeBottomLeft Then m.Result = New IntPtr(NCHitTest.Caption)
  64.  
  65.                    Case NCHitTest.BottomRight
  66.                        If Not Me.EnableResizeBottomRight Then m.Result = New IntPtr(NCHitTest.Caption)
  67.  
  68.                End Select
  69.  
  70.        End Select
  71.  
  72.    End Sub
  73.  
  74. #End Region

Ejemplo de uso:

Código
  1.    Private Sub Form_Shown() Handles MyBase.Shown
  2.        Me.EnableResizeTop = False
  3.        Me.EnableResizeBottom = False
  4.    End Sub
« Última modificación: 21 Noviembre 2013, 16:25 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #346 en: 22 Noviembre 2013, 14:46 pm »

Un ejemplo de uso de la librería DiffLib http://difflib.codeplex.com/releases/view/57226
Para comparar texto.



Código
  1. ' [ DiffLib Examples ]
  2. '
  3. ' // By Elektro H@cker
  4. '
  5. ' Instructions:
  6. '
  7. ' 1. Reference the "DiffLib.dll" into the project.
  8.  
  9.  
  10. #Region " DiffLib Examples "
  11.  
  12. Public Class Form1
  13.  
  14.    ReadOnly text1 As String = "This is a test of the Diff implementation, with some text that is deleted."
  15.    ReadOnly text2 As String = "This is another test of the same implementation, with some more text."
  16.  
  17.    Private Sub Test()
  18.  
  19.        HtmlLabel1.Text = DumpDiff(New DiffLib.Diff(Of Char)(text1, text2),
  20.                                   KnownColor.Black,
  21.                                   KnownColor.Black,
  22.                                   KnownColor.Black,
  23.                                   KnownColor.Transparent,
  24.                                   KnownColor.YellowGreen,
  25.                                   KnownColor.Red,
  26.                                   13)
  27.  
  28.    End Sub
  29.  
  30.    Private Function DumpDiff(ByVal changes As IEnumerable(Of DiffLib.DiffChange),
  31.                              ByVal Forecolor As KnownColor,
  32.                              ByVal ForecolorAdded As KnownColor,
  33.                              ByVal ForecolorDeleted As KnownColor,
  34.                              ByVal BackColor As KnownColor,
  35.                              ByVal BackColorAdded As KnownColor,
  36.                              ByVal BackColorDeleted As KnownColor,
  37.                              Optional ByVal FontSize As Integer = 10) As String
  38.  
  39.        Dim html As New System.Text.StringBuilder()
  40.  
  41.        Dim i1 As Integer = 0
  42.        Dim i2 As Integer = 0
  43.  
  44.        For Each change As DiffLib.DiffChange In changes
  45.  
  46.            If change.Equal Then
  47.  
  48.  
  49.                html.Append(String.Format("<span style='color: {0}; background-color: {1}; font-size: {2}pt'>{3}</span>",
  50.                                          Forecolor.ToString,
  51.                                          BackColor.ToString,
  52.                                          CStr(FontSize),
  53.                                          text1.Substring(i1, change.Length1)))
  54.  
  55.            Else
  56.  
  57.                html.Append(String.Format("<span style='color: {0}; background-color: {1}; font-size: {2}pt; text-decoration: line-through;'>{3}</span>",
  58.                                         ForecolorDeleted.ToString,
  59.                                         BackColorDeleted.ToString,
  60.                                          CStr(FontSize),
  61.                                         text1.Substring(i1, change.Length1)))
  62.  
  63.                html.Append(String.Format("<span style='color: {0}; background-color: {1}; font-size: {2}pt'>{3}</span>",
  64.                                         ForecolorAdded.ToString,
  65.                                         BackColorAdded.ToString,
  66.                                          CStr(FontSize),
  67.                                         text2.Substring(i2, change.Length2)))
  68.  
  69.            End If
  70.  
  71.            i1 += change.Length1
  72.            i2 += change.Length2
  73.  
  74.        Next change
  75.  
  76.        Return html.ToString
  77.  
  78.    End Function
  79.  
  80. End Class
  81.  
  82. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #347 en: 24 Noviembre 2013, 00:36 am »

un ayudante para la librería FTPClient http://netftp.codeplex.com/

Código
  1. Imports System.Net
  2. Imports System.Net.FtpClient
  3. Imports System.Net.FtpClient.Extensions
  4.  
  5. #Region " FTPClient Helper "
  6.  
  7. ' [ FTPClient Helper ]
  8. '
  9. ' // By Elektro H@cker
  10.  
  11. #Region " Usage Examples "
  12.  
  13. 'Public Class Form1
  14.  
  15. '    Private WithEvents UploadClient As New System.Net.WebClient()
  16. '    Private WithEvents DownloadClient As New System.Net.WebClient()
  17.  
  18. '    Private ftp As New FTP("sitio ftp", "username", "password")
  19.  
  20. '    Private Sub Test() Handles MyBase.Shown
  21.  
  22. '        ftp.Connect()
  23. '        ftp.CreateDirectory("/DirectoryName", True)
  24. '        ftp.UploadFile(UploadClient, "C:\File.txt", "/DirectoryName/NewFile.txt", False)
  25. '        ftp.DownloadFile(DownloadClient, "/DirectoryName/NewFile.txt", "c:\DownloadedFile.txt", True)
  26.  
  27. '    End Sub
  28.  
  29. '    Private Sub Client_UploadProgress(sender As System.Net.WebClient, e As System.Net.UploadProgressChangedEventArgs) _
  30. '    Handles UploadClient.UploadProgressChanged
  31.  
  32. '        Label_Upload.Text = e.ProgressPercentage & "%"
  33.  
  34. '    End Sub
  35.  
  36. '    Private Sub Client_UploadCompleted(sender As System.Net.WebClient, e As System.Net.UploadFileCompletedEventArgs) _
  37. '    Handles UploadClient.UploadFileCompleted
  38.  
  39. '        Label_UploadCompleted.Text = e.Result.ToString
  40.  
  41. '    End Sub
  42.  
  43. '    Private Sub Client_DownloadProgress(sender As System.Net.WebClient, e As System.Net.DownloadProgressChangedEventArgs) _
  44. '    Handles DownloadClient.DownloadProgressChanged
  45.  
  46. '        Label_Download.Text = e.ProgressPercentage & "%"
  47.  
  48. '    End Sub
  49.  
  50. '    Private Sub Client_DownloadCompleted(sender As System.Net.WebClient, e As System.ComponentModel.AsyncCompletedEventArgs) _
  51. '     Handles DownloadClient.DownloadFileCompleted
  52.  
  53. '        Label_DownloadCompleted.Text = "Done!"
  54.  
  55. '    End Sub
  56.  
  57. 'End Class
  58.  
  59. #End Region
  60.  
  61. Public Class FTP
  62.  
  63. #Region " Variables "
  64.  
  65.    Private conn As New FtpClient
  66.  
  67.    ''' <summary>
  68.    ''' The FTP site.
  69.    ''' </summary>
  70.    Private Property host As String = String.Empty
  71.  
  72.    ''' <summary>
  73.    ''' The user name.
  74.    ''' </summary>
  75.    Private Property user As String = String.Empty
  76.  
  77.    ''' <summary>
  78.    ''' The user password.
  79.    ''' </summary>
  80.    Private Property pass As String = String.Empty
  81.  
  82.    ' Friend m_reset As New ManualResetEvent(False) ' Use it for CallBacks
  83.  
  84. #End Region
  85.  
  86. #Region " Constructor "
  87.  
  88.    ''' <summary>
  89.    ''' .
  90.    ''' </summary>
  91.    ''' <param name="host">Indicates the ftp site.</param>
  92.    ''' <param name="user">Indicates the username.</param>
  93.    ''' <param name="pass">Indicates the password.</param>
  94.    Public Sub New(ByVal host As String,
  95.                   ByVal user As String,
  96.                   ByVal pass As String)
  97.  
  98.        If Not host.ToLower.StartsWith("ftp://") Then
  99.            Me.host = "ftp://" & host
  100.        Else
  101.            Me.host = host
  102.        End If
  103.  
  104.        If Me.host.Last = "/" Then
  105.            Me.host = Me.host.Remove(Me.host.Length - 1)
  106.        End If
  107.  
  108.        Me.user = user
  109.        Me.pass = pass
  110.  
  111.        With conn
  112.            .Host = If(host.Last = "/", host.Remove(host.Length - 1), host)
  113.            .Credentials = New NetworkCredential(Me.user, Me.pass)
  114.        End With
  115.  
  116.    End Sub
  117.  
  118. #End Region
  119.  
  120. #Region " Public Methods "
  121.  
  122.    ''' <summary>
  123.    ''' Connects to server.
  124.    ''' </summary>
  125.    Public Sub Connect()
  126.        conn.Connect()
  127.    End Sub
  128.  
  129.    ''' <summary>
  130.    ''' Disconnects from server.
  131.    ''' </summary>
  132.    Public Sub Disconnect()
  133.        conn.Disconnect()
  134.    End Sub
  135.  
  136.    ''' <summary>
  137.    ''' Creates a directory on server.
  138.    ''' </summary>
  139.    ''' <param name="directorypath">Indicates the ftp directory path.</param>
  140.    ''' <param name="force">Try to force all non-existant pieces of the path to be created.</param>
  141.    Public Sub CreateDirectory(ByVal directorypath As String, ByVal force As Boolean)
  142.        conn.CreateDirectory(directorypath, force)
  143.    End Sub
  144.  
  145.    ''' <summary>
  146.    ''' Creates a directory on server.
  147.    ''' </summary>
  148.    ''' <param name="directorypath">Indicates the ftp directory path.</param>
  149.    ''' <param name="force">Try to force all non-existant pieces of the path to be created.</param>
  150.    ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
  151.    Public Sub DeleteDirectory(ByVal directorypath As String,
  152.                               ByVal force As Boolean,
  153.                               Optional ByVal FtpListOption As FtpListOption =
  154.                               FtpListOption.AllFiles Or FtpListOption.ForceList)
  155.  
  156.        ' Remove the directory and all objects beneath it. The last parameter
  157.        ' forces System.Net.FtpClient to use LIST -a for getting a list of objects
  158.        ' beneath the specified directory.
  159.        conn.DeleteDirectory(directorypath, force, FtpListOption)
  160.  
  161.    End Sub
  162.  
  163.    ''' <summary>
  164.    ''' Deletes a file on server.
  165.    ''' </summary>
  166.    ''' <param name="filepath">Indicates the ftp file path.</param>
  167.    Public Sub DeleteFile(ByVal filepath As String)
  168.        conn.DeleteFile(filepath)
  169.    End Sub
  170.  
  171.    ''' <summary>
  172.    ''' Checks if a directory exist on server.
  173.    ''' </summary>
  174.    ''' <param name="directorypath">Indicates the ftp directory path.</param>
  175.    Public Function DirectoryExists(ByVal directorypath As String) As Boolean
  176.        Return conn.DirectoryExists(directorypath)
  177.    End Function
  178.  
  179.    ''' <summary>
  180.    ''' Executes a command on server.
  181.    ''' </summary>
  182.    ''' <param name="command">Indicates the command to execute on the server.</param>
  183.    ''' <returns>Returns an object containing the server reply information.</returns>
  184.    Public Function Execute(ByVal command As String) As FtpReply
  185.        Return (InlineAssignHelper(New FtpReply, conn.Execute(command)))
  186.    End Function
  187.  
  188.    ''' <summary>
  189.    ''' Tries to execute a command on server.
  190.    ''' </summary>
  191.    ''' <param name="command">Indicates the command to execute on the server.</param>
  192.    ''' <returns>Returns TRUE if command execution successfull, otherwise returns False.</returns>
  193.    Public Function TryExecute(ByVal command As String) As Boolean
  194.        Dim reply As FtpReply = Nothing
  195.        Return (InlineAssignHelper(reply, conn.Execute(command))).Success
  196.    End Function
  197.  
  198.    ''' <summary>
  199.    ''' Checks if a file exist on server.
  200.    ''' </summary>
  201.    ''' <param name="filepath">Indicates the ftp file path.</param>
  202.    ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
  203.    Public Function FileExists(ByVal filepath As String,
  204.                               Optional ByVal FtpListOption As FtpListOption =
  205.                               FtpListOption.AllFiles Or FtpListOption.ForceList) As Boolean
  206.  
  207.        ' The last parameter forces System.Net.FtpClient to use LIST -a
  208.        ' for getting a list of objects in the parent directory.
  209.        Return conn.FileExists(filepath, FtpListOption)
  210.  
  211.    End Function
  212.  
  213.    ''' <summary>
  214.    ''' Retrieves a checksum of the given file
  215.    ''' using a checksumming method that the server supports, if any.
  216.    ''' The algorithm used goes in this order:
  217.    ''' 1. HASH command (server preferred algorithm).
  218.    ''' 2. MD5 / XMD5 commands
  219.    ''' 3. XSHA1 command
  220.    ''' 4. XSHA256 command
  221.    ''' 5. XSHA512 command
  222.    ''' 6. XCRC command
  223.    ''' </summary>
  224.    ''' <param name="filepath">Indicates the ftp file path.</param>
  225.    Public Function GetChecksum(ByVal filepath As String) As FtpHash
  226.        Return conn.GetChecksum(filepath)
  227.    End Function
  228.  
  229.    ''' <summary>
  230.    ''' Gets the checksum of file on server and compare it with the checksum of local file.
  231.    ''' </summary>
  232.    ''' <param name="filepath">Indicates the ftp file path.</param>
  233.    ''' <param name="localfilepath">Indicates the local disk file path.</param>
  234.    ''' <param name="algorithm">Indicates the algorithm that should be used to verify checksums.</param>
  235.    ''' <returns>Returns TRUE if both checksums are equal, otherwise returns False.</returns>
  236.    Public Function VerifyChecksum(ByVal filepath As String,
  237.                                   ByVal localfilepath As String,
  238.                                   ByVal algorithm As FtpHashAlgorithm) As Boolean
  239.  
  240.        Dim hash As FtpHash = Nothing
  241.  
  242.        hash = conn.GetChecksum(filepath)
  243.        ' Make sure it returned a, to the best of our knowledge, valid hash object.
  244.        ' The commands for retrieving checksums are
  245.        ' non-standard extensions to the protocol so we have to
  246.        ' presume that the response was in a format understood by
  247.        ' System.Net.FtpClient and parsed correctly.
  248.        '
  249.        ' In addition, there is no built-in support for verifying CRC hashes.
  250.        ' You will need to write you own or use a third-party solution.
  251.        If hash.IsValid AndAlso hash.Algorithm <> algorithm Then
  252.            Return hash.Verify(localfilepath)
  253.        Else
  254.            Return Nothing
  255.        End If
  256.  
  257.    End Function
  258.  
  259.    ''' <summary>
  260.    ''' Gets the size of file.
  261.    ''' </summary>
  262.    ''' <param name="filepath">Indicates the ftp file path.</param>
  263.    Public Function GetFileSize(ByVal filepath As String) As Long
  264.        Return conn.GetFileSize(filepath)
  265.    End Function
  266.  
  267.    ''' <summary>
  268.    ''' Gets the currently HASH algorithm used for the HASH command on server.
  269.    ''' </summary>
  270.    Public Function GetHashAlgorithm() As FtpHashAlgorithm
  271.        Return conn.GetHashAlgorithm()
  272.    End Function
  273.  
  274.    ''' <summary>
  275.    ''' Gets the modified time of file.
  276.    ''' </summary>
  277.    ''' <param name="filepath">Indicates the ftp file path.</param>
  278.    Public Function GetModifiedTime(ByVal filepath As String) As Date
  279.        Return conn.GetModifiedTime(filepath)
  280.    End Function
  281.  
  282.    ''' <summary>
  283.    ''' Returns a file/directory listing using the NLST command.
  284.    ''' </summary>
  285.    ''' <param name="directorypath">Indicates the ftp file path.</param>
  286.    Public Function GetNameListing(ByVal directorypath As String) As String()
  287.        Return conn.GetNameListing(directorypath)
  288.    End Function
  289.  
  290.    ''' <summary>
  291.    ''' Gets the current working directory on server.
  292.    ''' </summary>
  293.    Public Function GetWorkingDirectory() As String
  294.        Return conn.GetWorkingDirectory()
  295.    End Function
  296.  
  297.    ''' <summary>
  298.    ''' Opens the specified file to be appended to...
  299.    ''' </summary>
  300.    ''' <param name="filepath">Indicates the ftp file path.</param>
  301.    Public Function OpenAppend(ByVal filepath As String) As IO.Stream
  302.        Return conn.OpenAppend(filepath)
  303.    End Function
  304.  
  305.    ''' <summary>
  306.    ''' Opens the specified file for reading.
  307.    ''' </summary>
  308.    ''' <param name="filepath">Indicates the ftp file path.</param>
  309.    Public Function OpenRead(ByVal filepath As String) As IO.Stream
  310.        Return conn.OpenRead(filepath)
  311.    End Function
  312.  
  313.    ''' <summary>
  314.    ''' Opens the specified file for writing.
  315.    ''' </summary>
  316.    ''' <param name="filepath">Indicates the ftp file path.</param>
  317.    Public Function OpenWrite(ByVal filepath As String) As IO.Stream
  318.        Return conn.OpenWrite(filepath)
  319.    End Function
  320.  
  321.    ''' <summary>
  322.    ''' Rename a file on the server.
  323.    ''' </summary>
  324.    ''' <param name="filepath">Indicates the ftp file path.</param>
  325.    ''' <param name="newfilepath">Indicates the new ftp file path.</param>
  326.    Public Sub RenameFile(ByVal filepath As String, ByVal newfilepath As String)
  327.        If conn.FileExists(filepath) Then
  328.            conn.Rename(filepath, newfilepath)
  329.        Else
  330.            Throw New Exception(filepath & " File does not exist on server.")
  331.        End If
  332.    End Sub
  333.  
  334.    ''' <summary>
  335.    ''' Rename a directory on the server.
  336.    ''' </summary>
  337.    ''' <param name="directorypath">Indicates the ftp file path.</param>
  338.    ''' <param name="newdirectorypath">Indicates the new ftp file path.</param>
  339.    Public Sub RenameDirectory(ByVal directorypath As String, ByVal newdirectorypath As String)
  340.        If conn.DirectoryExists(directorypath) Then
  341.            conn.Rename(directorypath, newdirectorypath)
  342.        Else
  343.            Throw New Exception(directorypath & " Directory does not exist on server.")
  344.        End If
  345.    End Sub
  346.  
  347.    ''' <summary>
  348.    ''' Tells the server wich hash algorithm to use for the HASH command.
  349.    ''' </summary>
  350.    ''' <param name="algorithm">Indicates the HASH algorithm.</param>
  351.    Public Function SetHashAlgorithm(ByVal algorithm As FtpHashAlgorithm) As Boolean
  352.        If conn.HashAlgorithms.HasFlag(algorithm) Then
  353.            conn.SetHashAlgorithm(algorithm)
  354.            Return True
  355.        Else
  356.            Return False
  357.        End If
  358.    End Function
  359.  
  360.    ''' <summary>
  361.    ''' Sets the working directory on the server.
  362.    ''' </summary>
  363.    ''' <param name="directorypath">Indicates the ftp directory path.</param>
  364.    Public Sub SetWorkingDirectory(ByVal directorypath As String)
  365.        conn.SetWorkingDirectory(directorypath)
  366.    End Sub
  367.  
  368.    ''' <summary>
  369.    ''' Gets a directory list on the specified path.
  370.    ''' </summary>
  371.    ''' <param name="directorypath">Indicates the ftp directory path.</param>
  372.    ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
  373.    Public Function GetDirectories(ByVal directorypath As String,
  374.                                   Optional ByVal FtpListOption As FtpListOption =
  375.                                   FtpListOption.AllFiles) As FtpListItem()
  376.  
  377.        Return conn.GetListing(directorypath, FtpListOption).
  378.               Where(Function(item) item.Type = FtpFileSystemObjectType.Directory)
  379.  
  380.    End Function
  381.  
  382.    ''' <summary>
  383.    ''' Gets a file list on the specified path.
  384.    ''' </summary>
  385.    ''' <param name="directorypath">Indicates the ftp directory path.</param>
  386.    ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
  387.    Public Function GetFiles(ByVal directorypath As String,
  388.                             Optional ByVal FtpListOption As FtpListOption =
  389.                             FtpListOption.AllFiles) As FtpListItem()
  390.  
  391.        Return conn.GetListing(directorypath, FtpListOption).
  392.               Where(Function(item) item.Type = FtpFileSystemObjectType.File)
  393.  
  394.    End Function
  395.  
  396.    ''' <summary>
  397.    ''' Gets a link list on the specified path.
  398.    ''' </summary>
  399.    ''' <param name="directorypath">Indicates the ftp directory path.</param>
  400.    ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
  401.    Public Function GetLinks(ByVal directorypath As String,
  402.                             Optional ByVal FtpListOption As FtpListOption =
  403.                             FtpListOption.AllFiles) As FtpListItem()
  404.  
  405.        Return conn.GetListing(directorypath, FtpListOption).
  406.               Where(Function(item) item.Type = FtpFileSystemObjectType.Link)
  407.  
  408.    End Function
  409.  
  410.    ''' <summary>
  411.    ''' Gets a file/folder list on the specified path.
  412.    ''' </summary>
  413.    ''' <param name="directorypath">Indicates the ftp directory path.</param>
  414.    ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
  415.    Public Function GetListing(ByVal directorypath As String,
  416.                               Optional ByVal FtpListOption As FtpListOption =
  417.                               FtpListOption.AllFiles) As FtpListItem()
  418.  
  419.        Return conn.GetListing(directorypath, FtpListOption)
  420.  
  421.    End Function
  422.  
  423.    ''' <summary>
  424.    ''' Log to a console window
  425.    ''' </summary>
  426.    Public Sub LogToConsole()
  427.        FtpTrace.AddListener(New ConsoleTraceListener())
  428.        ' now use System.Net.FtpCLient as usual and the server transactions
  429.        ' will be written to the Console window.
  430.    End Sub
  431.  
  432.    ''' <summary>
  433.    ''' Log to a text file
  434.    ''' </summary>
  435.    ''' <param name="filepath">Indicates the file where to save the log.</param>
  436.    Public Sub LogToFile(ByVal filepath As String)
  437.        FtpTrace.AddListener(New TextWriterTraceListener(filepath))
  438.        ' now use System.Net.FtpCLient as usual and the server transactions
  439.        ' will be written to the specified log file.
  440.    End Sub
  441.  
  442.    ''' <summary>
  443.    ''' Uploads a file from FTP.
  444.    ''' </summary>
  445.    ''' <param name="UploadClient">Indicates the WebClient object to upload the file.</param>
  446.    ''' <param name="filepath">Indicates the ftp fle path.</param>
  447.    ''' <param name="localfilepath">Specifies the local path where to save the downloaded file.</param>
  448.    ''' <param name="Asynchronous">Indicates whether the download should be an Asynchronous operation,
  449.    ''' to raise WebClient events.</param>
  450.    Public Sub UploadFile(ByRef UploadClient As WebClient,
  451.                          ByVal localfilepath As String,
  452.                          Optional ByVal filepath As String = Nothing,
  453.                          Optional ByVal Asynchronous As Boolean = False)
  454.  
  455.        If filepath Is Nothing Then
  456.            filepath = Me.host & "/" & New IO.FileInfo(localfilepath).Name
  457.        ElseIf filepath.StartsWith("/") Then
  458.            filepath = Me.host & filepath
  459.        Else
  460.            filepath = Me.host & "/" & filepath
  461.        End If
  462.  
  463.        With UploadClient
  464.            .Credentials = New NetworkCredential(Me.user, Me.pass)
  465.            If Asynchronous Then
  466.                .UploadFileAsync(New Uri(filepath), "STOR", localfilepath)
  467.            Else
  468.                .UploadFile(New Uri(filepath), "STOR", localfilepath)
  469.            End If
  470.        End With
  471.    End Sub
  472.  
  473.    ''' <summary>
  474.    ''' Downloads a file from FTP.
  475.    ''' </summary>
  476.    ''' <param name="DownloadClient">Indicates the WebClient object to download the file.</param>
  477.    ''' <param name="filepath">Indicates the ftp fle path.</param>
  478.    ''' <param name="localfilepath">Specifies the local path where to save the downloaded file.</param>
  479.    ''' <param name="Asynchronous">Indicates whether the download should be an Asynchronous operation,
  480.    ''' to raise WebClient events.</param>
  481.    Public Sub DownloadFile(ByRef DownloadClient As WebClient,
  482.                            ByVal filepath As String,
  483.                            ByVal localfilepath As String,
  484.                            Optional ByVal Asynchronous As Boolean = False)
  485.  
  486.        If filepath.StartsWith("/") Then
  487.            filepath = Me.host & filepath
  488.        Else
  489.            filepath = Me.host & "/" & filepath
  490.        End If
  491.  
  492.        MsgBox(filepath)
  493.        With DownloadClient
  494.            .Credentials = New NetworkCredential(Me.user, Me.pass)
  495.            If Asynchronous Then
  496.                .DownloadFileAsync(New Uri(filepath), localfilepath)
  497.            Else
  498.                .DownloadFile(New Uri(filepath), localfilepath)
  499.            End If
  500.        End With
  501.    End Sub
  502.  
  503. #End Region
  504.  
  505. #Region " Miscellaneous methods "
  506.  
  507.    Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
  508.        target = value
  509.        Return value
  510.    End Function
  511.  
  512. #End Region
  513.  
  514. End Class
  515.  
  516. #End Region
« Última modificación: 24 Noviembre 2013, 00:40 am por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #348 en: 25 Noviembre 2013, 01:42 am »

Un ayudante para agregar y/o eliminar variables de entorno en el sistema.

Código
  1. #Region " Environment Variables Helper "
  2.  
  3. ' [ Environment Variables Helper ]
  4. '
  5. ' // By Elektro H@cker
  6. '
  7. ' Examples:
  8. ' EnvironmentVariables.Add("DirFiles", "Dir /B ""*.*""", EnvironmentVariables.EnvironmentKind.CurrentUser)
  9. ' EnvironmentVariables.Remove("DirFiles", EnvironmentVariables.EnvironmentKind.CurrentUser)
  10.  
  11. Public Class EnvironmentVariables
  12.  
  13. #Region " API, Constants, Enums"
  14.  
  15.    ''' <summary>
  16.    ''' User Environment Subkey.
  17.    ''' </summary>
  18.    Private Shared ReadOnly UserEnvironmentKey As String = "Environment\"
  19.  
  20.    ''' <summary>
  21.    ''' System Environment Subkey.
  22.    ''' </summary>
  23.    Private Shared ReadOnly SystemEnvironmentKey As String = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment\"
  24.  
  25.    ''' <summary>
  26.    ''' Sends the specified message to one or more windows.
  27.    ''' </summary>
  28.    <System.Runtime.InteropServices.
  29.    DllImport("user32.dll", SetLastError:=True)> _
  30.    Public Shared Function SendMessageTimeout(
  31.                  ByVal windowHandle As IntPtr,
  32.                  ByVal Msg As Integer,
  33.                  ByVal wParam As IntPtr,
  34.                  ByVal lParam As String,
  35.                  ByVal flags As SendMessageTimeoutFlags,
  36.                  ByVal timeout As Integer,
  37.                  ByRef result As IntPtr
  38.    ) As IntPtr
  39.    End Function
  40.  
  41.    ''' <summary>
  42.    ''' Kind of environment.
  43.    ''' </summary>
  44.    Public Enum EnvironmentKind As Short
  45.  
  46.        ''' <summary>
  47.        ''' Indicates that the environment variable
  48.        ''' should only be accesible for the current user.
  49.        ''' </summary>
  50.        CurrentUser = 0
  51.  
  52.        ''' <summary>
  53.        ''' Indicates that the environment variable
  54.        ''' should be accesible for all users.
  55.        ''' </summary>
  56.        System = 1
  57.  
  58.    End Enum
  59.  
  60.    ''' <summary>
  61.    ''' Sends the specified message to one or more windows.
  62.    ''' </summary>
  63.    <Flags()> _
  64.    Public Enum SendMessageTimeoutFlags As Integer
  65.  
  66.        ''' <summary>
  67.        ''' The calling thread is not prevented from processing
  68.        ''' other requests while waiting for the function to return.
  69.        ''' </summary>
  70.        SMTO_NORMAL = &H0
  71.  
  72.        ''' <summary>
  73.        ''' Prevents the calling thread from processing any other requests until the function returns.
  74.        ''' </summary>
  75.        SMTO_BLOCK = &H1
  76.  
  77.        ''' <summary>
  78.        ''' The function returns without waiting for the time-out period
  79.        ''' to elapse if the receiving thread appears to not respond or "hangs."
  80.        ''' </summary>
  81.        SMTO_ABORTIFHUNG = &H2
  82.  
  83.        ''' <summary>
  84.        ''' The function does not enforce the time-out period
  85.        ''' as long as the receiving thread is processing messages.
  86.        ''' </summary>
  87.        SMTO_NOTIMEOUTIFNOTHUNG = &H8
  88.  
  89.        ''' <summary>
  90.        ''' The function should return 0 if the receiving window is destroyed
  91.        ''' or its owning thread dies while the message is being processed.
  92.        ''' </summary>
  93.        SMTO_ERRORONEXIT = &H20
  94.  
  95.    End Enum
  96.  
  97.    ''' <summary>
  98.    ''' A message that is sent to all top-level windows when
  99.    ''' the SystemParametersInfo function changes a system-wide setting or when policy settings have changed.
  100.    ''' <remarks>
  101.    ''' Applications should send WM_SETTINGCHANGE to all top-level windows when they make changes to system parameters
  102.    ''' (This message cannot be sent directly to a window.)
  103.    '''  To send the WM_SETTINGCHANGE message to all top-level windows,
  104.    ''' use the SendMessageTimeout function with the hwnd parameter set to HWND_BROADCAST.
  105.    ''' </remarks>
  106.    ''' </summary>
  107.    Private Const WM_SETTINGCHANGE = &H1A
  108.  
  109.    ''' <summary>
  110.    ''' the message is sent to all top-level windows in the system,
  111.    ''' including disabled or invisible unowned windows.
  112.    ''' The function does not return until each window has timed out.
  113.    ''' Therefore, the total wait time can be up to the value of uTimeout multiplied by the number of top-level windows.
  114.    ''' </summary>
  115.    Public Const HWND_BROADCAST = &HFFFF&
  116.  
  117. #End Region
  118.  
  119. #Region " Public methods "
  120.  
  121.    ''' <summary>
  122.    ''' Sets an environment variable.
  123.    ''' <remarks>If a variable already exists, will be replaced.</remarks>
  124.    ''' </summary>
  125.    ''' <param name="VariableName">Indicates the variable name.</param>
  126.    ''' <param name="Value">Indicates the variable value.</param>
  127.    ''' <param name="EnvironmentKind">Indicates the kind of environment where the variable should be added.</param>
  128.    Public Shared Sub Add(ByVal VariableName As String,
  129.                   ByVal Value As String,
  130.                   ByVal EnvironmentKind As EnvironmentKind)
  131.  
  132.        Select Case EnvironmentKind
  133.  
  134.            Case EnvironmentKind.CurrentUser
  135.                My.Computer.Registry.CurrentUser.
  136.                    OpenSubKey(UserEnvironmentKey, True).
  137.                    SetValue(VariableName, Value)
  138.  
  139.            Case EnvironmentKind.System
  140.                My.Computer.Registry.LocalMachine.
  141.                    OpenSubKey(SystemEnvironmentKey, True).
  142.                    SetValue(VariableName, Value)
  143.  
  144.        End Select
  145.  
  146.        UpdateRegChange()
  147.  
  148.    End Sub
  149.  
  150.    ''' <summary>
  151.    ''' Sets an environment variable.
  152.    ''' </summary>
  153.    ''' <param name="VariableName">Indicates the variable name.</param>
  154.    ''' <param name="EnvironmentKind">Indicates the kind of environment from where the variable should be removed.</param>
  155.    Public Shared Sub Remove(ByVal VariableName As String,
  156.                      ByVal EnvironmentKind As EnvironmentKind)
  157.  
  158.        Select Case EnvironmentKind
  159.  
  160.            Case EnvironmentKind.CurrentUser
  161.                My.Computer.Registry.CurrentUser.
  162.                    OpenSubKey(UserEnvironmentKey, True).
  163.                    DeleteValue(VariableName, True)
  164.  
  165.            Case EnvironmentKind.System
  166.                My.Computer.Registry.LocalMachine.
  167.                    OpenSubKey(SystemEnvironmentKey, True).
  168.                    DeleteValue(VariableName, True)
  169.  
  170.        End Select
  171.  
  172.        UpdateRegChange()
  173.  
  174.    End Sub
  175.  
  176. #End Region
  177.  
  178. #Region " Private methods "
  179.  
  180.    Private Shared Sub UpdateRegChange()
  181.  
  182.        ' Update Registry Change
  183.        SendMessageTimeout(HWND_BROADCAST,
  184.                           WM_SETTINGCHANGE,
  185.                           0,
  186.                           "Environment",
  187.                           SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,
  188.                           1,
  189.                           IntPtr.Zero)
  190.  
  191.    End Sub
  192.  
  193. #End Region
  194.  
  195. End Class
  196.  
  197. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Posteen aquí sus snippets)
« Respuesta #349 en: 26 Noviembre 2013, 12:43 pm »

Un ejemplo de uso de la librería FrameworkDetection http://www.codeproject.com/Articles/17501/Using-managed-code-to-detect-what-NET-Framework-ve?msg=4706288#xx4706288xx



Código
  1. Public Class Form1
  2.  
  3.    Private Sub Test()
  4.  
  5.        Dim sb As New System.Text.StringBuilder
  6.  
  7.        For Each FW In [Enum].GetValues(GetType(Campari.Software.FrameworkVersion))
  8.  
  9.            sb.AppendLine(String.Format("FW {0} Is installed?: {1}",
  10.                                        FW.ToString.Substring(2),
  11.                                        Campari.Software.FrameworkVersionDetection.IsInstalled(FW)))
  12.  
  13.            sb.AppendLine(String.Format("FW {0} version: {1}",
  14.                                        FW.ToString.Substring(2),
  15.                                        Campari.Software.FrameworkVersionDetection.GetExactVersion(FW).ToString))
  16.  
  17.            sb.Append(Environment.NewLine)
  18.  
  19.        Next
  20.  
  21.        MsgBox(sb.ToString)
  22.  
  23.    End Sub
  24.  
  25. End Class
En línea

Páginas: 1 ... 20 21 22 23 24 25 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 ... 58 Ir Arriba Respuesta Imprimir 

Ir a:  

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