Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)

Iniciado por Eleкtro, 18 Diciembre 2012, 22:23 PM

0 Miembros y 1 Visitante están viendo este tema.

Eleкtro

#340
El equivalente al sizeof de C#:

Código (vbnet) [Seleccionar]
#Region " SizeOf "

   ' [ SizeOf ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   '
   ' MsgBox(SizeOf(1L))      ' Result: 8
   ' MsgBox(SizeOf(Of Long)) ' Result: 8

   Public Function SizeOf(Of T)() As Integer

       Try
           Return System.Runtime.InteropServices.Marshal.SizeOf(GetType(T))
       Catch ex As ArgumentException
           Return -1
       End Try

   End Function

   Public Function SizeOf(ByVal [Object] As Object) As Integer

       Try
           Return System.Runtime.InteropServices.Marshal.SizeOf([Object])
       Catch ex As ArgumentNullException
           Return -1
       Catch ex As ArgumentException
           Return -1
       End Try

   End Function

#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 (vbnet) [Seleccionar]
       Dim Hbitmap As IntPtr = CType(PictureBox1.Image, Bitmap).GetHbitmap()
       PictureBox2.BackgroundImage = Image.FromHbitmap(Hbitmap)


Código (vbnet) [Seleccionar]
   Private Function Get_Image_HBitmap(ByVal Image As Image) As IntPtr
       Return CType(Image, Bitmap).GetHbitmap()
   End Function








Eleкtro

#341
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 (vbnet) [Seleccionar]
FileDate.Action("C:\File.txt", FileDate.FileDateAction.Save)
IO.File.AppendAllText("C:\File.txt", "Hello World!")
FileDate.Action("C:\File.txt", FileDate.FileDateAction.Restore)


O bien:

Código (vbnet) [Seleccionar]
FileDate.Action("C:\File.txt", FileDate.FileDateAction.Save, False)
IO.File.AppendAllText("C:\File.txt", "Hello World!")
IO.File.Move("C:\File.txt", "C:\File.log")
FileDate.Action(New IO.FileInfo("C:\File.log"), FileDate.FileDateAction.Restore, False)





Código (vbnet) [Seleccionar]
#Region " Preserve FileDate "

' [ Preserve FileDate ]
'
' // By Elektro H@cker
'
' Usage Examples:

' // Example 1:
'
' FileDate.Action("C:\File.txt", FileDate.FileDateAction.Save)
' IO.File.AppendAllText("C:\File.txt", "Hello World!")
' FileDate.Action("C:\File.txt", FileDate.FileDateAction.Restore)

' // Example 2:
'
' FileDate.Action("C:\File.txt", FileDate.FileDateAction.Save, False)
' IO.File.AppendAllText("C:\File.txt", "Hello World!")
' IO.File.Move("C:\File.txt", "C:\File.log")
' FileDate.Action(New IO.FileInfo("C:\File.log"), FileDate.FileDateAction.Restore, False)

Public Class FileDate

    ''' <summary>
    ''' Collection that contains the files and their dates.
    ''' </summary>
    Private Shared FileDates As New Dictionary(Of String, Date())

    ''' <summary>
    ''' Stores the File object.
    ''' </summary>
    Private Shared _File As IO.FileInfo

    ''' <summary>
    ''' Stores the full path of the file
    ''' </summary>
    Private Shared FullPath As String

    ''' <summary>
    ''' An action to take on file dates.
    ''' </summary>
    Public Enum FileDateAction As Short

        ''' <summary>
        ''' Save file dates into filedates collection.
        ''' </summary>
        Save = 0

        ''' <summary>
        ''' Restore file dates from filedates collection.
        ''' </summary>
        Restore = 1

        ''' <summary>
        ''' Remove file dates from filedates collection,
        ''' this don't removes the dates from file.
        ''' </summary>
        Remove = 2

        ''' <summary>
        ''' Sets the file dates of specified file to "01/01/1800 00:00:00"
        ''' </summary>
        Truncate = 3

    End Enum

    ''' <summary>
    ''' Performs an action on the dates of the specified file,
    ''' Creation Date, LastAccess Date and LastWrite Date.
    ''' </summary>
    ''' <param name="File">
    ''' The File.
    ''' </param>
    ''' <param name="Action">
    ''' The action to take on file dates.
    ''' </param>
    ''' <param name="IncludeFileExtension">
    ''' Specifies if that the filename extension should be included or not.
    ''' Default value is <paramref name="True"/>.
    ''' This parameter should be set to <paramref name="False"/>  when renaming files.
    ''' </param>
    Public Shared Sub Action(ByVal File As IO.FileInfo,
                             ByVal Action As FileDateAction,
                             Optional ByVal IncludeFileExtension As Boolean = True)

        _File = File
        DoFileDateAction(_File, Action, IncludeFileExtension)

    End Sub

    ''' <summary>
    ''' Performs an action on the dates of the specified file,
    ''' Creation Date, LastAccess Date and LastWrite Date.
    ''' </summary>
    ''' <param name="File">
    ''' The File.
    ''' </param>
    ''' <param name="Action">
    ''' The action to take on file dates.
    ''' </param>
    ''' <param name="IncludeFileExtension">
    ''' Specifies if that the filename extension should be included or not.
    ''' Default value is <paramref name="True"/>.
    ''' This parameter should be set to <paramref name="False"/> when renaming files.
    ''' </param>
    Public Shared Sub Action(ByVal File As String,
                             ByVal Action As FileDateAction,
                             Optional ByVal IncludeFileExtension As Boolean = True)

        _File = New IO.FileInfo(File)
        DoFileDateAction(_File, Action, IncludeFileExtension)

    End Sub

    ''' <summary>
    ''' Clears all the dates stored in the filedates collection.
    ''' </summary>
    Public Shared Sub ClearFileDateCollection()
        FileDates.Clear()
    End Sub

    ''' <summary>
    ''' Perform an action to take on file dates.
    ''' </summary>
    Private Shared Sub DoFileDateAction(ByVal File As IO.FileInfo,
                                        ByVal Action As FileDateAction,
                                        ByVal IncludeFileExtension As Boolean)

        FullPath = If(IncludeFileExtension,
                      File.FullName,
                      If(File.Name.Contains("."),
                         File.FullName.Substring(0, File.FullName.LastIndexOf(".")),
                         File.FullName))

        HandleErrors(Action)

        Select Case Action

            Case FileDateAction.Save

                FileDates.Add(FullPath,
                             {File.CreationTime, File.LastAccessTime, File.LastWriteTime})

            Case FileDateAction.Restore

                File.CreationTime = FileDates(FullPath).First
                File.LastAccessTime = FileDates(FullPath)(1)
                File.LastWriteTime = FileDates(FullPath).Last

                FileDates.Remove(FullPath)

            Case FileDateAction.Remove

                FileDates.Remove(FullPath)

            Case FileDateAction.Truncate
                File.CreationTime = "01/01/1800 00:00:00"
                File.LastAccessTime = "01/01/1800 00:00:00"
                File.LastWriteTime = "01/01/1800 00:00:00"

        End Select

    End Sub

    ''' <summary>
    ''' Simple Error Handling.
    ''' </summary>
    Private Shared Sub HandleErrors(ByVal Action As FileDateAction)

        Select Case Action

            Case FileDateAction.Save

                If FileDates.ContainsKey(FullPath) Then
                    Throw New Exception("File already exist in collection.")
                End If

            Case FileDateAction.Restore, FileDateAction.Remove

                If Not FileDates.ContainsKey(FullPath) Then
                    Throw New Exception("File not found in collection.")
                End If

        End Select


    End Sub

End Class

#End Region








Eleкtro

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









Eleкtro

Shortcut Manager

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

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

#Region " ShortcutManager "

' [ ShortcutManager ]
'
' // By Elektro H@cker

#Region " Usage Examples "

'Private Sub Test()

'    ' Tries to resolve a shortcut which has changed their Target location.
'    ShortcutManager.Resolve_Ui("C:\Truncated Shortcut.lnk", New IntPtr(1))
'    ShortcutManager.Resolve_NoUi("C:\Truncated Shortcut.lnk")

'    ' Creates a new Shortcut file
'    ShortcutManager.Create("C:\Shortcut.lnk",
'                           "C:\TargetFile.ext",
'                           "C:\",
'                           "Description",
'                           "-Arguments",
'                           "C:\Icon.ico", 0,
'                           ShortcutManager.HotkeyModifiers.ALT Or ShortcutManager.HotkeyModifiers.CONTROL,
'                           Keys.F1,
'                           ShortcutManager.ShortcutWindowState.Normal)

'    ' Gets Shortcut file information
'    Dim ShortcutInfo As ShortcutManager.ShortcutInfo =
'        ShortcutManager.GetInfo("C:\Shortcut.lnk")

'    Dim sb As New System.Text.StringBuilder

'    With ShortcutInfo

'        sb.AppendLine(String.Format(" ""{0}"" ", .ShortcutFile))
'        sb.AppendLine(String.Format("------------------------"))
'        sb.AppendLine(String.Format("Description: {0}", .Description))
'        sb.AppendLine(String.Format("Target: {0}", .Target))
'        sb.AppendLine(String.Format("Arguments: {0}", .Arguments))
'        sb.AppendLine(String.Format("Target Is Directory?: {0}", CStr(.IsDirectory)))
'        sb.AppendLine(String.Format("Target Is File?: {0}", CStr(.IsFile)))
'        sb.AppendLine(String.Format("WorkingDir: {0}", .WorkingDir))
'        sb.AppendLine(String.Format("DirectoryName: {0}", .DirectoryName))
'        sb.AppendLine(String.Format("FileName: {0}", .FileName))
'        sb.AppendLine(String.Format("FileExtension: {0}", .FileExtension))
'        sb.AppendLine(String.Format("DriveLetter: {0}", .DriveLetter))
'        sb.AppendLine(String.Format("Icon: {0}", .Icon))
'        sb.AppendLine(String.Format("Icon Index: {0}", CStr(.IconIndex)))
'        sb.AppendLine(String.Format("Hotkey (Hex): {0}", CStr(.Hotkey)))
'        sb.AppendLine(String.Format("Hotkey (Str): {0} + {1}", .Hotkey_Modifier.ToString, .Hotkey_Key.ToString))
'        sb.AppendLine(String.Format("Window State: {0}", .WindowState.ToString))

'    End With

'    MsgBox(sb.ToString)

'End Sub

#End Region

Public Class ShortcutManager

#Region " Variables "

    Private Shared lnk As New ShellLink()
    Private Shared lnk_data As New WIN32_FIND_DATAW()

    Private Shared lnk_arguments As New StringBuilder(260)
    Private Shared lnk_description As New StringBuilder(260)
    Private Shared lnk_target As New StringBuilder(260)
    Private Shared lnk_workingdir As New StringBuilder(260)
    Private Shared lnk_iconpath As New StringBuilder(260)
    Private Shared lnk_iconindex As Integer = -1
    Private Shared lnk_hotkey As Short = -1
    Private Shared lnk_windowstate As ShortcutWindowState = ShortcutWindowState.Normal

#End Region

#Region " API, Interfaces, Enumerations "

    <DllImport("shfolder.dll",
    CharSet:=CharSet.Auto)>
    Friend Shared Function SHGetFolderPath(ByVal hwndOwner As IntPtr,
                                           ByVal nFolder As Integer,
                                           ByVal hToken As IntPtr,
                                           ByVal dwFlags As Integer,
                                           ByVal lpszPath As StringBuilder
    ) As Integer
    End Function

    <Flags()>
    Private Enum SLGP_FLAGS

        ''' <summary>
        ''' Retrieves the standard short (8.3 format) file name.
        ''' </summary>
        SLGP_SHORTPATH = &H1

        ''' <summary>
        ''' Retrieves the Universal Naming Convention (UNC) path name of the file.
        ''' </summary>
        SLGP_UNCPRIORITY = &H2

        ''' <summary>
        ''' Retrieves the raw path name.
        ''' A raw path is something that might not exist and may include environment variables that need to be expanded.
        ''' </summary>
        SLGP_RAWPATH = &H4

    End Enum

    <Flags()>
    Private Enum SLR_FLAGS

        ''' <summary>
        ''' Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
        ''' the high-order word of fFlags can be set to a time-out value that specifies the
        ''' maximum amount of time to be spent resolving the link. The function returns if the
        ''' link cannot be resolved within the time-out duration. If the high-order word is set
        ''' to zero, the time-out duration will be set to the default value of 3,000 milliseconds
        ''' (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
        ''' duration, in milliseconds.
        ''' </summary>
        SLR_NO_UI = &H1

        ''' <summary>
        ''' If the link object has changed, update its path and list of identifiers.
        ''' If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine,
        ''' whether or not the link object has changed.
        ''' </summary>
        SLR_UPDATE = &H4

        ''' <summary>
        ''' Do not update the link information
        ''' </summary>
        SLR_NOUPDATE = &H8

        ''' <summary>
        ''' Do not execute the search heuristics
        ''' </summary>
        SLR_NOSEARCH = &H10

        ''' <summary>
        ''' Do not use distributed link tracking
        ''' </summary>
        SLR_NOTRACK = &H20

        ''' <summary>
        ''' Disable distributed link tracking.
        ''' By default, distributed link tracking tracks removable media,
        ''' across multiple devices based on the volume name.
        ''' It also uses the Universal Naming Convention (UNC) path to track remote file systems,
        ''' whose drive letter has changed.
        ''' Setting SLR_NOLINKINFO disables both types of tracking.
        ''' </summary>
        SLR_NOLINKINFO = &H40

        ''' <summary>
        ''' Call the Microsoft Windows Installer
        ''' </summary>
        SLR_INVOKE_MSI = &H80

    End Enum

    ''' <summary>
    ''' Stores information about a shortcut file.
    ''' </summary>
    Public Class ShortcutInfo

        ''' <summary>
        ''' Shortcut file full path.
        ''' </summary>
        Public Property ShortcutFile As String

        ''' <summary>
        ''' Shortcut Comment/Description.
        ''' </summary>
        Public Property Description As String

        ''' <summary>
        ''' Shortcut Target Arguments.
        ''' </summary>
        Public Property Arguments As String

        ''' <summary>
        ''' Shortcut Target.
        ''' </summary>
        Public Property Target As String

        ''' <summary>
        ''' Shortcut Working Directory.
        ''' </summary>
        Public Property WorkingDir As String

        ''' <summary>
        ''' Shortcut Icon Location.
        ''' </summary>
        Public Property Icon As String

        ''' <summary>
        ''' Shortcut Icon Index.
        ''' </summary>
        Public Property IconIndex As Integer

        ''' <summary>
        ''' Shortcut Hotkey combination.
        ''' Is represented as Hexadecimal.
        ''' </summary>
        Public Property Hotkey As Short

        ''' <summary>
        ''' Shortcut Hotkey modifiers.
        ''' </summary>
        Public Property Hotkey_Modifier As HotkeyModifiers

        ''' <summary>
        ''' Shortcut Hotkey Combination.
        ''' </summary>
        Public Property Hotkey_Key As Keys

        ''' <summary>
        ''' Shortcut Window State.
        ''' </summary>
        Public Property WindowState As ShortcutWindowState

        ''' <summary>
        ''' Indicates if the target is a file.
        ''' </summary>
        Public Property IsFile As Boolean

        ''' <summary>
        ''' Indicates if the target is a directory.
        ''' </summary>
        Public Property IsDirectory As Boolean

        ''' <summary>
        ''' Shortcut target drive letter.
        ''' </summary>
        Public Property DriveLetter As String

        ''' <summary>
        ''' Shortcut target directory name.
        ''' </summary>
        Public Property DirectoryName As String

        ''' <summary>
        ''' Shortcut target filename.
        ''' (File extension is not included in name)
        ''' </summary>
        Public Property FileName As String

        ''' <summary>
        ''' Shortcut target file extension.
        ''' </summary>
        Public Property FileExtension As String

    End Class

    ''' <summary>
    ''' Hotkey modifiers for a shortcut file.
    ''' </summary>
    <FlagsAttribute()>
    Public Enum HotkeyModifiers As Short

        ''' <summary>
        ''' The SHIFT key.
        ''' </summary>
        SHIFT = 1

        ''' <summary>
        ''' The CTRL key.
        ''' </summary>
        CONTROL = 2

        ''' <summary>
        ''' The ALT key.
        ''' </summary>
        ALT = 4

        ''' <summary>
        ''' None.
        ''' Specifies any hotkey modificator.
        ''' </summary>
        NONE = 0

    End Enum

    ''' <summary>
    ''' The Window States for a shortcut file.
    ''' </summary>
    Public Enum ShortcutWindowState As Integer

        ''' <summary>
        ''' Shortcut Window is at normal state.
        ''' </summary>
        Normal = 1

        ''' <summary>
        ''' Shortcut Window is Maximized.
        ''' </summary>
        Maximized = 3

        ''' <summary>
        ''' Shortcut Window is Minimized.
        ''' </summary>
        Minimized = 7

    End Enum

    <StructLayout(LayoutKind.Sequential,
    CharSet:=CharSet.Auto)>
    Private Structure WIN32_FIND_DATAW
        Public dwFileAttributes As UInteger
        Public ftCreationTime As Long
        Public ftLastAccessTime As Long
        Public ftLastWriteTime As Long
        Public nFileSizeHigh As UInteger
        Public nFileSizeLow As UInteger
        Public dwReserved0 As UInteger
        Public dwReserved1 As UInteger
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)>
        Public cFileName As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=14)>
        Public cAlternateFileName As String
    End Structure

    ''' <summary>
    ''' The IShellLink interface allows Shell links to be created, modified, and resolved
    ''' </summary>
    <ComImport(),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    Guid("000214F9-0000-0000-C000-000000000046")>
    Private Interface IShellLinkW

        ''' <summary>
        ''' Retrieves the path and file name of a Shell link object.
        ''' </summary>
        Sub GetPath(<Out(), MarshalAs(UnmanagedType.LPWStr)>
                    ByVal pszFile As StringBuilder,
                    ByVal cchMaxPath As Integer,
                    ByRef pfd As WIN32_FIND_DATAW,
                    ByVal fFlags As SLGP_FLAGS)

        ''' <summary>
        ''' Retrieves the list of item identifiers for a Shell link object.
        ''' </summary>
        Sub GetIDList(ByRef ppidl As IntPtr)

        ''' <summary>
        ''' Sets the pointer to an item identifier list (PIDL) for a Shell link object.
        ''' </summary>
        Sub SetIDList(ByVal pidl As IntPtr)

        ''' <summary>
        ''' Retrieves the description string for a Shell link object.
        ''' </summary>
        Sub GetDescription(<Out(), MarshalAs(UnmanagedType.LPWStr)>
                           ByVal pszName As StringBuilder,
                           ByVal cchMaxName As Integer)

        ''' <summary>
        ''' Sets the description for a Shell link object.
        ''' The description can be any application-defined string.
        ''' </summary>
        Sub SetDescription(<MarshalAs(UnmanagedType.LPWStr)>
                           ByVal pszName As String)

        ''' <summary>
        ''' Retrieves the name of the working directory for a Shell link object.
        ''' </summary>
        Sub GetWorkingDirectory(<Out(), MarshalAs(UnmanagedType.LPWStr)>
                                ByVal pszDir As StringBuilder,
                                ByVal cchMaxPath As Integer)

        ''' <summary>
        ''' Sets the name of the working directory for a Shell link object.
        ''' </summary>
        Sub SetWorkingDirectory(<MarshalAs(UnmanagedType.LPWStr)>
                                ByVal pszDir As String)

        ''' <summary>
        ''' Retrieves the command-line arguments associated with a Shell link object.
        ''' </summary>
        Sub GetArguments(<Out(), MarshalAs(UnmanagedType.LPWStr)>
                         ByVal pszArgs As StringBuilder,
                         ByVal cchMaxPath As Integer)

        ''' <summary>
        ''' Sets the command-line arguments for a Shell link object.
        ''' </summary>
        Sub SetArguments(<MarshalAs(UnmanagedType.LPWStr)>
                         ByVal pszArgs As String)

        ''' <summary>
        ''' Retrieves the hot key for a Shell link object.
        ''' </summary>
        Sub GetHotkey(ByRef pwHotkey As Short)

        ''' <summary>
        ''' Sets a hot key for a Shell link object.
        ''' </summary>
        Sub SetHotkey(ByVal wHotkey As Short)

        ''' <summary>
        ''' Retrieves the show command for a Shell link object.
        ''' </summary>
        Sub GetShowCmd(ByRef piShowCmd As Integer)

        ''' <summary>
        ''' Sets the show command for a Shell link object.
        ''' The show command sets the initial show state of the window.
        ''' </summary>
        Sub SetShowCmd(ByVal iShowCmd As ShortcutWindowState)

        ''' <summary>
        ''' Retrieves the location (path and index) of the icon for a Shell link object.
        ''' </summary>
        Sub GetIconLocation(<Out(), MarshalAs(UnmanagedType.LPWStr)>
                            ByVal pszIconPath As StringBuilder,
                            ByVal cchIconPath As Integer,
                            ByRef piIcon As Integer)

        ''' <summary>
        ''' Sets the location (path and index) of the icon for a Shell link object.
        ''' </summary>
        Sub SetIconLocation(<MarshalAs(UnmanagedType.LPWStr)>
                            ByVal pszIconPath As String,
                            ByVal iIcon As Integer)

        ''' <summary>
        ''' Sets the relative path to the Shell link object.
        ''' </summary>
        Sub SetRelativePath(<MarshalAs(UnmanagedType.LPWStr)>
                            ByVal pszPathRel As String,
                            ByVal dwReserved As Integer)

        ''' <summary>
        ''' Attempts to find the target of a Shell link,
        ''' even if it has been moved or renamed.
        ''' </summary>
        Sub Resolve(ByVal hwnd As IntPtr,
                    ByVal fFlags As SLR_FLAGS)

        ''' <summary>
        ''' Sets the path and file name of a Shell link object
        ''' </summary>
        Sub SetPath(ByVal pszFile As String)

    End Interface

    <ComImport(), Guid("0000010c-0000-0000-c000-000000000046"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
    Public Interface IPersist

        <PreserveSig()>
        Sub GetClassID(ByRef pClassID As Guid)

    End Interface

    <ComImport(), Guid("0000010b-0000-0000-C000-000000000046"),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
    Public Interface IPersistFile
        Inherits IPersist

        Shadows Sub GetClassID(ByRef pClassID As Guid)

        <PreserveSig()>
        Function IsDirty() As Integer

        <PreserveSig()>
        Sub Load(<[In](), MarshalAs(UnmanagedType.LPWStr)>
                 pszFileName As String,
                 dwMode As UInteger)

        <PreserveSig()>
        Sub Save(<[In](), MarshalAs(UnmanagedType.LPWStr)>
                 pszFileName As String,
                 <[In](), MarshalAs(UnmanagedType.Bool)>
                 fRemember As Boolean)

        <PreserveSig()>
        Sub SaveCompleted(<[In](), MarshalAs(UnmanagedType.LPWStr)>
                          pszFileName As String)

        <PreserveSig()>
        Sub GetCurFile(<[In](), MarshalAs(UnmanagedType.LPWStr)>
                       ppszFileName As String)

    End Interface

    ' "CLSID_ShellLink" from "ShlGuid.h"
    <ComImport(),
    Guid("00021401-0000-0000-C000-000000000046")>
    Public Class ShellLink
    End Class

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Resolves the target of a shortcut.
    ''' If shortcut can't be resolved, an error message would be displayed.
    ''' This is usefull when the target path of a shortcut file is changed from a driveletter for example,
    ''' then the shortcut file need to be resolved before trying to retrieve the target path.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to resolve.
    ''' </param>
    ''' <param name="hwnd">
    ''' The new handle pointer that would be generated
    ''' for the window which should display the error message (if any).
    ''' </param>
    Public Shared Sub Resolve_Ui(ShortcutFile As String, hwnd As IntPtr)
        LoadShortcut(ShortcutFile)
        DirectCast(lnk, IShellLinkW).Resolve(hwnd, SLR_FLAGS.SLR_UPDATE)
    End Sub

    ''' <summary>
    ''' Resolves the target of a shortcut.
    ''' If shortcut can't be resolved, any error message would be displayed.
    ''' This is usefull when the target path of a shortcut file is changed from a driveletter for example,
    ''' then the shortcut file need to be resolved before trying to retrieve the target path.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to resolve.
    ''' </param>
    Public Shared Sub Resolve_NoUi(ByVal ShortcutFile As String)
        LoadShortcut(ShortcutFile)
        DirectCast(lnk, IShellLinkW).Resolve(IntPtr.Zero, SLR_FLAGS.SLR_UPDATE Or SLR_FLAGS.SLR_NO_UI)
    End Sub

    ''' <summary>
    ''' Returns the description of a shortcut file.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to retrieve the info.
    ''' </param>
    Public Shared Function Get_Description(ByVal ShortcutFile As String) As String
        LoadShortcut(ShortcutFile)
        lnk_description.Clear()
        DirectCast(lnk, IShellLinkW).GetDescription(lnk_description, lnk_description.Capacity)
        Return lnk_description.ToString()
    End Function

    ''' <summary>
    ''' Returns the Arguments of a shortcut file.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to retrieve the info.
    ''' </param>
    Public Shared Function Get_Arguments(ByVal ShortcutFile As String) As String
        LoadShortcut(ShortcutFile)
        lnk_arguments.Clear()
        DirectCast(lnk, IShellLinkW).GetArguments(lnk_arguments, lnk_arguments.Capacity)
        Return lnk_arguments.ToString()
    End Function

    ''' <summary>
    ''' Returns the path and filename of a shortcut file.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to retrieve the info.
    ''' </param>
    Public Shared Function Get_FullPath(ByVal ShortcutFile As String) As String
        LoadShortcut(ShortcutFile)
        lnk_target.Clear()
        DirectCast(lnk, IShellLinkW).GetPath(lnk_target, lnk_target.Capacity, lnk_data, SLGP_FLAGS.SLGP_UNCPRIORITY)
        Return lnk_target.ToString()
    End Function

    ''' <summary>
    ''' Returns the working directory of a shortcut file.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to retrieve the info.
    ''' </param>
    Public Shared Function Get_WorkingDir(ByVal ShortcutFile As String) As String
        LoadShortcut(ShortcutFile)
        lnk_workingdir.Clear()
        DirectCast(lnk, IShellLinkW).GetWorkingDirectory(lnk_workingdir, lnk_workingdir.Capacity)
        Return lnk_workingdir.ToString()
    End Function

    ''' <summary>
    ''' Returns the Hotkey of a shortcut file.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to retrieve the info.
    ''' </param>
    Public Shared Function Get_Hotkey(ByVal ShortcutFile As String) As Short
        LoadShortcut(ShortcutFile)
        lnk_hotkey = -1
        DirectCast(lnk, IShellLinkW).GetHotkey(lnk_hotkey)
        Return lnk_hotkey
    End Function

    ''' <summary>
    ''' Returns the Window State of a shortcut file.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to retrieve the info.
    ''' </param>
    Public Shared Function Get_WindowStyle(ByVal ShortcutFile As String) As ShortcutWindowState
        LoadShortcut(ShortcutFile)
        DirectCast(lnk, IShellLinkW).GetShowCmd(lnk_windowstate)
        Return lnk_windowstate
    End Function

    ''' <summary>
    ''' Returns the Icon location of a shortcut file.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to retrieve the info.
    ''' </param>
    ''' <param name="IconIndex">
    ''' Optional Integer type variable to store the IconIndex.
    ''' </param>
    Public Shared Function Get_IconLocation(ByVal ShortcutFile As String,
                                            Optional ByRef IconIndex As Integer = 0) As String
        LoadShortcut(ShortcutFile)
        lnk_iconpath.Clear()
        DirectCast(lnk, IShellLinkW).GetIconLocation(lnk_iconpath, lnk_iconpath.Capacity, IconIndex)
        Return lnk_iconpath.ToString()
    End Function

    ''' <summary>
    ''' Retrieves all the information about a shortcut file.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to retrieve the info.
    ''' </param>
    Public Shared Function GetInfo(ByVal ShortcutFile As String) As ShortcutInfo

        ' Load Shortcut
        LoadShortcut(ShortcutFile)

        ' Clean objects
        lnk_description.Clear()
        lnk_arguments.Clear()
        lnk_target.Clear()
        lnk_workingdir.Clear()
        lnk_iconpath.Clear()
        lnk_hotkey = -1
        lnk_iconindex = -1

        ' Retrieve Info
        DirectCast(lnk, IShellLinkW).GetDescription(lnk_description, lnk_description.Capacity)
        DirectCast(lnk, IShellLinkW).GetArguments(lnk_arguments, lnk_arguments.Capacity)
        DirectCast(lnk, IShellLinkW).GetPath(lnk_target, lnk_target.Capacity, lnk_data, SLGP_FLAGS.SLGP_UNCPRIORITY)
        DirectCast(lnk, IShellLinkW).GetWorkingDirectory(lnk_workingdir, lnk_workingdir.Capacity)
        DirectCast(lnk, IShellLinkW).GetIconLocation(lnk_iconpath, lnk_iconpath.Capacity, lnk_iconindex)
        DirectCast(lnk, IShellLinkW).GetHotkey(lnk_hotkey)
        DirectCast(lnk, IShellLinkW).GetShowCmd(lnk_windowstate)

        ' Return Info
        Return New ShortcutInfo With {
            .ShortcutFile = ShortcutFile,
            .Description = lnk_description.ToString,
            .Arguments = lnk_arguments.ToString,
            .Target = lnk_target.ToString,
            .Icon = lnk_iconpath.ToString,
            .IconIndex = lnk_iconindex,
            .WorkingDir = lnk_workingdir.ToString,
            .Hotkey = Hex(lnk_hotkey),
            .Hotkey_Modifier = [Enum].Parse(GetType(HotkeyModifiers), GetHiByte(lnk_hotkey)),
            .Hotkey_Key = [Enum].Parse(GetType(Keys), GetLoByte(lnk_hotkey)),
            .WindowState = lnk_windowstate,
            .IsFile = File.Exists(lnk_target.ToString),
            .IsDirectory = Directory.Exists(lnk_target.ToString),
            .DriveLetter = lnk_target.ToString.Substring(0, 1),
            .DirectoryName = lnk_target.ToString.Substring(0, lnk_target.ToString.LastIndexOf("\")),
            .FileName = lnk_target.ToString.Split("\").LastOrDefault.Split(".").FirstOrDefault,
            .FileExtension = lnk_target.ToString.Split(".").LastOrDefault
        }

    End Function

    ''' <summary>
    ''' Creates a shortcut file.
    ''' </summary>
    ''' <param name="FilePath">
    ''' The filepath to create the shortcut.
    ''' </param>
    ''' <param name="Target">
    ''' The target file or directory.
    ''' </param>
    ''' <param name="WorkingDirectory">
    ''' The working directory os the shortcut.
    ''' </param>
    ''' <param name="Description">
    ''' The shortcut description.
    ''' </param>
    ''' <param name="Arguments">
    ''' The target file arguments.
    ''' This value only should be set when target is an executable file.
    ''' </param>
    ''' <param name="Icon">
    ''' The icon location of the shortcut.
    ''' </param>
    ''' <param name="IconIndex">
    ''' The icon index of the icon file.
    ''' </param>
    ''' <param name="HotKey_Modifier">
    ''' The hotkey modifier(s) which should be used for the hotkey combination.
    ''' <paramref name="HotkeyModifiers"/> can be one or more modifiers.
    ''' </param>
    ''' <param name="HotKey_Key">
    ''' The key used in combination with the <paramref name="HotkeyModifiers"/> for hotkey combination.
    ''' </param>
    ''' <param name="WindowState">
    ''' The Window state for the target.
    ''' </param>
    Public Shared Sub Create(ByVal FilePath As String,
                             ByVal Target As String,
                             Optional ByVal WorkingDirectory As String = Nothing,
                             Optional ByVal Description As String = Nothing,
                             Optional ByVal Arguments As String = Nothing,
                             Optional ByVal Icon As String = Nothing,
                             Optional ByVal IconIndex As Integer = Nothing,
                             Optional ByVal HotKey_Modifier As HotkeyModifiers = Nothing,
                             Optional ByVal HotKey_Key As Keys = Nothing,
                             Optional ByVal WindowState As ShortcutWindowState = ShortcutWindowState.Normal)

        LoadShortcut(FilePath)

        DirectCast(lnk, IShellLinkW).SetPath(Target)

        DirectCast(lnk, IShellLinkW).SetWorkingDirectory(If(WorkingDirectory IsNot Nothing,
                                                            WorkingDirectory,
                                                            Path.GetDirectoryName(Target)))

        DirectCast(lnk, IShellLinkW).SetDescription(Description)
        DirectCast(lnk, IShellLinkW).SetArguments(Arguments)
        DirectCast(lnk, IShellLinkW).SetIconLocation(Icon, IconIndex)

        DirectCast(lnk, IShellLinkW).SetHotkey(If(HotKey_Modifier + HotKey_Key <> 0,
                                                  Convert.ToInt32(CInt(HotKey_Modifier & Hex(HotKey_Key)), 16),
                                                  Nothing))

        DirectCast(lnk, IShellLinkW).SetShowCmd(WindowState)

        DirectCast(lnk, IPersistFile).Save(FilePath, True)
        DirectCast(lnk, IPersistFile).SaveCompleted(FilePath)

    End Sub

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Loads the shortcut object to retrieve information.
    ''' </summary>
    ''' <param name="ShortcutFile">
    ''' The shortcut file to retrieve the info.
    ''' </param>
    Private Shared Sub LoadShortcut(ByVal ShortcutFile As String)
        DirectCast(lnk, IPersistFile).Load(ShortcutFile, 0)
    End Sub

    ''' <summary>
    ''' Gets the low order byte of a number.
    ''' </summary>
    Private Shared Function GetLoByte(ByVal Intg As Integer) As Integer
        Return Intg And &HFF&
    End Function

    ''' <summary>
    ''' Gets the high order byte of a number.
    ''' </summary>
    Private Shared Function GetHiByte(ByVal Intg As Integer) As Integer
        Return (Intg And &HFF00&) / 256
    End Function

#End Region

End Class

#End Region








Eleкtro

#344
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 (vbnet) [Seleccionar]



' [ FFMPEG Helper ]
'
' // By Elektro H@cker
'
' Instructions:
'
' 1. Add the "FFMPEG.exe" into the project


#Region " FFMPEG Helper "

#Region " Usage Examples "

'Public Class Form1

'    Private WithEvents _FFMPEG As New FFMPEG With
'    {.FFMPEG_location = "C:\windows\system32\ffmpeg.exe", .CheckFileExist = False}

'    Private Shadows Sub Shown() Handles MyBase.Shown

'        ' Checks if FFMPEG executable is avaliable.
'        MsgBox(_FFMPEG.Is_Avaliable())

'        ' Checks if a video has metadata
'        MsgBox(_FFMPEG.HasMetadata("C:\Video.mkv"))

'        ' Remove metadata from video
'        _FFMPEG.RemoveMetadata("C:\Input.mkv", "C:\Output.mkv", True, 4)

'        ' reCompress the audio track of a video
'        _FFMPEG.Recompress_AudioTrack("C:\Input.mkv", "C:\Output.mkv", True,
'                                      FFMPEG.AudioCodec.libmp3lame, FFMPEG.AudioBitRate.kbps_128, 4)

'    End Sub

'    ' FFMPEG [Started]
'    Private Sub FFMPEG_Started(ByVal sender As Process, ByVal e As FFMPEG.StartedEventArgs) _
'    Handles _FFMPEG.Started

'        ProgressBar1.Value = ProgressBar1.Minimum

'        Dim sb As New System.Text.StringBuilder

'        sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString))
'        sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
'        sb.AppendLine(String.Format("FFMPEG process PID is: ""{0}""", CStr(sender.Id)))

'        MessageBox.Show(sb.ToString, "FFMPEG", MessageBoxButtons.OK, MessageBoxIcon.Information)

'    End Sub

'    ' FFMPEG [Exited]
'    Private Sub FFMPEG_Exited(ByVal sender As Process, ByVal e As FFMPEG.ExitedEventArgs) _
'    Handles _FFMPEG.Exited

'        Dim sb As New System.Text.StringBuilder

'        sb.AppendLine(String.Format("Finished an ""{0}"" operation", e.Operation.ToString))
'        sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
'        sb.AppendLine(String.Format("FFMPEG process PID is: {0}", CStr(sender.Id)))

'        If e.Errors.Count <> 0 Then
'            sb.AppendLine(String.Format("Errors during operation: {0}", String.Join(Environment.NewLine, e.Errors)))
'        End If

'        MessageBox.Show(sb.ToString, "FFMPEG", MessageBoxButtons.OK, MessageBoxIcon.Information)

'    End Sub

'    ' FFMPEG [Progress]
'    Private Sub FFMPEG_Progress(sender As Process, e As FFMPEG.ProgressEventArgs) _
'    Handles _FFMPEG.Progress

'        ProgressBar1.Value = e.Percent

'        Label1.Text = "Percent Done: " & CStr(e.Percent) & "%"
'        Label2.Text = "Video Duration: " & e.VideoDuration.ToString("hh\:mm\:ss")
'        Label3.Text = "Written Duration: " & e.Time.ToString("hh\:mm\:ss")
'        Label4.Text = "Written Data: " & (e.WrittenBytes / 1024L * 1024L).ToString("n1") & "MB"

'    End Sub

'End Class

#End Region

#Region " CommandLine Parameter legend "

'-y        | Overwrite output files without asking.
'-n        | Do not overwrite output files, and exit immediately if a specified output file already exists.
'-threads: |  Specify the cpu threads to use.
'-nostdin  | Disable interaction on standard input.
'-vcodec   | Set the video codec.
'-acodec   | Set the audio codec.
'-vn       | Disable video recording.
'-an       | Disable audio recording.

' -c copy -map_metadata -1
' Don't add metadata.

#End Region

Public Class FFMPEG : Implements IDisposable

#Region " Variables, Properties, Enumerations "

   ''' <summary>
   ''' Gets or sets FFMPEG.exe executable path.
   ''' </summary>
   Public Property FFMPEG_location As String = ".\FFMPEG.exe"

   ''' <summary>
   ''' Unique temp file to write FFMPEG output.
   ''' </summary>
   Private ReadOnly TempFile As String = IO.Path.GetTempFileName

   ''' <summary>
   ''' Indicates if should check that the file exist before realize an operation.
   ''' If True, an exception would be launched if file does not exist.
   ''' </summary>
   Public Property CheckFileExist As Boolean = False

   ''' <summary>
   ''' Stores the next FFMEP process output line.
   ''' </summary>
   Private OutputLine As String = Nothing

   ''' <summary>
   ''' Stores the Video Duration.
   ''' </summary>
   Private VideoDuration As TimeSpan = Nothing

   ''' <summary>
   ''' Stores the processed video time.
   ''' </summary>
   Private Time As TimeSpan = Nothing

   ''' <summary>
   ''' Stores the conversion errors (if any).
   ''' </summary>
   Private Errors As New List(Of String)

   ''' <summary>
   ''' Stores the StartedEventArgs Arguments.
   ''' </summary>
   Private StartedArgs As New StartedEventArgs

   ''' <summary>
   ''' Stores the ExitedEventArgs Arguments.
   ''' </summary>
   Private ExitedArgs As New ExitedEventArgs

   ''' <summary>
   ''' Stores the ProgressEventArgs Arguments.
   ''' </summary>
   Private ProgressArgs As New ProgressEventArgs

   ''' <summary>
   ''' FFMPEG kind Of Operation.
   ''' </summary>
   Public Enum Operation As Short
       Check_Metadata = 0
       Remove_Metadata = 1
       Recompress_AudioTrack = 2
   End Enum

   ''' <summary>
   ''' FFMPEG Process.
   ''' </summary>
   Private p As Process =
       New Process With {.StartInfo =
           New ProcessStartInfo With {
               .CreateNoWindow = True, _
               .UseShellExecute = False, _
               .RedirectStandardError = True, _
               .RedirectStandardOutput = True, _
               .StandardErrorEncoding = System.Text.Encoding.Default, _
               .StandardOutputEncoding = System.Text.Encoding.Default
          }
       }

   ''' <summary>
   ''' Audio Codec use for the conversion.
   ''' </summary>
   Public Enum AudioCodec

       ''' <summary>
       ''' MP3 Audio.
       ''' </summary>
       libmp3lame

       ''' <summary>
       ''' Windows Media Audio.
       ''' </summary>
       wmav2

   End Enum

   ''' <summary>
   ''' BitRate used for the audio compression.
   ''' </summary>
   Public Enum AudioBitRate As Integer
       kbps_24 = 24
       kbps_32 = 32
       kbps_40 = 40
       kbps_48 = 48
       kbps_56 = 56
       kbps_64 = 64
       kbps_80 = 80
       kbps_96 = 96
       kbps_112 = 112
       kbps_128 = 128
       kbps_144 = 144
       kbps_160 = 160
       kbps_192 = 192
       kbps_224 = 224
       kbps_256 = 256
       kbps_320 = 320
   End Enum

#End Region

#Region " Events "

   ''' <summary>
   ''' Event raised when FFMPEG operation progress changes.
   ''' </summary>
   Public Event Progress As EventHandler(Of ProgressEventArgs)
   Public Class ProgressEventArgs : Inherits EventArgs

       ''' <summary>
       ''' The FFMPEG operation percent done.
       ''' </summary>
       Public Property Percent As Integer

       ''' <summary>
       ''' The Input Video Duration.
       ''' </summary>
       Public Property VideoDuration As TimeSpan

       ''' <summary>
       ''' The processed video time.
       ''' </summary>
       Public Property Time As TimeSpan

       ''' <summary>
       ''' The total amount of written bytes.
       ''' </summary>
       Public Property WrittenBytes As Double

   End Class

   ''' <summary>
   ''' Event raised when FFMPEG process has started.
   ''' </summary>
   Public Event Started As EventHandler(Of StartedEventArgs)
   Public Class StartedEventArgs : Inherits EventArgs

       ''' <summary>
       ''' Gets the file that was passed as argument to the process.
       ''' </summary>
       Public Property File As String

       ''' <summary>
       ''' Gets the type of operation to realize.
       ''' </summary>
       Public Property Operation As Operation

   End Class

   ''' <summary>
   ''' Event raised when FFMPEG process has exited.
   ''' </summary>
   Public Event Exited As EventHandler(Of ExitedEventArgs)
   Public Class ExitedEventArgs : Inherits EventArgs

       ''' <summary>
       ''' Gets the file that was passed as argument to the process.
       ''' </summary>
       Public Property File As String

       ''' <summary>
       ''' Gets the type of operation to realize.
       ''' </summary>
       Public Property Operation As Operation

       ''' <summary>
       ''' Gets an error message of the realized operation (if any).
       ''' </summary>
       Public Property Errors As List(Of String)

   End Class

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Checks if FFMPEG process is avaliable.
   ''' </summary>
   Public Function Is_Avaliable() As Boolean
       Return IO.File.Exists(Me.FFMPEG_location)
   End Function

   ''' <summary>
   ''' Checks if a video file contains metadata fields.
   ''' </summary>
   Public Function HasMetadata(ByVal VideoFile As String) As Boolean

       DisposedCheck()

       p.StartInfo.Arguments =
         String.Format("-y -i ""{0}"" -f ffmetadata ""{1}""",
                       VideoFile,
                       TempFile)

       Run_FFMPEG(VideoFile, Operation.Check_Metadata)

       Return IO.File.ReadAllText(TempFile).Replace(";FFMETADATA1", "").Trim.Length <> 0

   End Function

   ''' <summary>
   ''' Removes the metadata tags from a video file.
   ''' </summary>
   Public Sub RemoveMetadata(ByVal VideoFile As String,
                             ByVal OutputFile As String,
                             ByVal OverWrite As Boolean,
                             Optional ByVal Threads As Integer = 1)

       DisposedCheck()

       p.StartInfo.Arguments =
         String.Format("-nostdin -threads {2} {3} -i ""{0}"" -c copy -map_metadata -1 ""{1}""",
                       VideoFile,
                       OutputFile,
                       Threads,
                       If(OverWrite, "-y", "-n"))

       Run_FFMPEG(VideoFile, Operation.Remove_Metadata)

   End Sub

   ''' <summary>
   ''' ReCompress the audio track of a video file.
   ''' </summary>
   Public Sub Recompress_AudioTrack(ByVal VideoFile As String,
                                    ByVal OutputFile As String,
                                    ByVal OverWrite As Boolean,
                                    ByVal AudioCodec As AudioCodec,
                                    ByVal Bitrate As AudioBitRate,
                                    Optional ByVal CopyMetadata As Boolean = False,
                                    Optional ByVal Threads As Integer = 1)

       DisposedCheck()

       p.StartInfo.Arguments =
         String.Format("-nostdin -threads {2} {3} -i ""{0}"" {6} -vcodec copy -acodec {4} -ab {5} ""{1}""",
                       VideoFile,
                       OutputFile,
                       Threads,
                       If(OverWrite, "-y", "-n"),
                       AudioCodec.ToString,
                       CStr(Bitrate) & "k",
                       If(CopyMetadata, "", "-c copy -map_metadata -1"))

       Run_FFMPEG(VideoFile, Operation.Recompress_AudioTrack)

   End Sub

#End Region

#Region " Run Method "

   ''' <summary>
   ''' Runs a specific operation of FFMPEG.
   ''' </summary>
   Private Sub Run_FFMPEG(ByVal file As String,
                          ByVal Operation As Operation)

       If Me.CheckFileExist Then
           FileExist(file)
       End If

       VideoDuration = Nothing
       Errors.Clear()

       p.StartInfo.FileName = Me.FFMPEG_location
       p.Start()

       With StartedArgs
           .File = file
           .Operation = Operation
       End With

       RaiseEvent Started(p, StartedArgs)

       While Not p.StandardError.EndOfStream

           ' Parse the Input Video Duration to calculate the percentage.
           Do Until VideoDuration.TotalMilliseconds > 0

               OutputLine = p.StandardError.ReadLine.ToLower

               If OutputLine.Contains("duration") Then

                   Try
                       VideoDuration = TimeSpan.Parse(OutputLine.Replace("duration:", "").
                                                                 Split(",").FirstOrDefault)
                   Catch ex As FormatException
                       VideoDuration = TimeSpan.Parse("24:00:00") ' 00:00:00
                   End Try

               End If
           Loop

           ' Parse the percentage and other values.
           OutputLine = p.StandardError.ReadLine.ToLower

           If OutputLine.StartsWith("frame=") Then

               Time = TimeSpan.Parse(OutputLine.Split("=")(5).Split.First)

               With ProgressArgs
                   .VideoDuration = VideoDuration
                   .Time = Time
                   .Percent = (Time.TotalSeconds / VideoDuration.TotalSeconds) * 100
                   .WrittenBytes = CDbl(OutputLine.Split("=")(4).Trim.Split.First.Replace("kb", "")) / 1024
               End With

               RaiseEvent Progress(p, ProgressArgs)

           ElseIf (OutputLine.Contains("error") OrElse OutputLine.Contains("warning")) Then
               Errors.Add(OutputLine)
#If DEBUG Then
               ' MsgBox("[DEBUG] FFMPEG Error: " & OutputLine)
#End If
           End If

       End While

       With ExitedArgs
           .File = file
           .Operation = Operation
           .Errors = Errors
       End With

       RaiseEvent Exited(p, ExitedArgs)

       ' FFMPEG.Close()

   End Sub

#End Region

#Region " Miscellaneous Methods "

   ''' <summary>
   ''' Checks if a file exists.
   ''' </summary>
   Private Sub FileExist(ByVal File As String)

       If Not IO.File.Exists(File) Then
           ' Throw New Exception("File doesn't exist: " & File)
           MessageBox.Show("File doesn't exist: " & File, "FFMPEG", MessageBoxButtons.OK, MessageBoxIcon.Error)
       End If

   End Sub

#End Region

#Region " IDisposable "

   ''' <summary>
   ''' To detect redundant calls when disposing.
   ''' </summary>
   Private IsDisposed As Boolean = False

   ''' <summary>
   ''' Prevents calls to methods after disposing.
   ''' </summary>
   Private Sub DisposedCheck()
       If Me.IsDisposed Then
           Throw New ObjectDisposedException(Me.GetType().FullName)
       End If
   End Sub

   ''' <summary>
   ''' Disposes the objects generated by this instance.
   ''' </summary>
   Public Sub Dispose() Implements IDisposable.Dispose
       Dispose(True)
       GC.SuppressFinalize(Me)
   End Sub

   ' IDisposable
   Protected Overridable Sub Dispose(IsDisposing As Boolean)

       If Not Me.IsDisposed Then

           If IsDisposing Then
               p.Dispose()
           End If

       End If

       Me.IsDisposed = True

   End Sub

#End Region

End Class

#End Region



Un ejemplo de uso:

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

   Private WithEvents _FFMPEG As New FFMPEG With
   {.FFMPEG_location = "C:\windows\system32\ffmpeg.exe", .CheckFileExist = False}

   Private Shadows Sub Shown() Handles MyBase.Shown

       ' Checks if FFMPEG executable is avaliable.
       MsgBox(_FFMPEG.Is_Avaliable())

       ' Checks if a video has metadata
       MsgBox(_FFMPEG.HasMetadata("C:\Video.mkv"))

       ' Remove metadata from video
       _FFMPEG.RemoveMetadata("C:\Input.mkv", "C:\Output.mkv", True, 4)

       ' reCompress the audio track of a video
       _FFMPEG.Recompress_AudioTrack("C:\Input.mkv", "C:\Output.mkv", True,
                                     FFMPEG.AudioCodec.libmp3lame, FFMPEG.AudioBitRate.kbps_128, 4)

   End Sub

   ' FFMPEG [Started]
   Private Sub FFMPEG_Started(ByVal sender As Process, ByVal e As FFMPEG.StartedEventArgs) _
   Handles _FFMPEG.Started

       ProgressBar1.Value = ProgressBar1.Minimum

       Dim sb As New System.Text.StringBuilder

       sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString))
       sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
       sb.AppendLine(String.Format("FFMPEG process PID is: ""{0}""", CStr(sender.Id)))

       MessageBox.Show(sb.ToString, "FFMPEG", MessageBoxButtons.OK, MessageBoxIcon.Information)

   End Sub

   ' FFMPEG [Exited]
   Private Sub FFMPEG_Exited(ByVal sender As Process, ByVal e As FFMPEG.ExitedEventArgs) _
   Handles _FFMPEG.Exited

       Dim sb As New System.Text.StringBuilder

       sb.AppendLine(String.Format("Finished an ""{0}"" operation", e.Operation.ToString))
       sb.AppendLine(String.Format("Input file is: ""{0}""", e.File))
       sb.AppendLine(String.Format("FFMPEG process PID is: {0}", CStr(sender.Id)))

       If e.Errors.Count <> 0 Then
           sb.AppendLine(String.Format("Errors during operation: {0}", String.Join(Environment.NewLine, e.Errors)))
       End If

       MessageBox.Show(sb.ToString, "FFMPEG", MessageBoxButtons.OK, MessageBoxIcon.Information)

   End Sub

   ' FFMPEG [Progress]
   Private Sub FFMPEG_Progress(sender As Process, e As FFMPEG.ProgressEventArgs) _
   Handles _FFMPEG.Progress

       ProgressBar1.Value = e.Percent

       Label1.Text = "Percent Done: " & CStr(e.Percent) & "%"
       Label2.Text = "Video Duration: " & e.VideoDuration.ToString("hh\:mm\:ss")
       Label3.Text = "Written Duration: " & e.Time.ToString("hh\:mm\:ss")
       Label4.Text = "Written Data: " & (e.WrittenBytes / 1024L * 1024L).ToString("n1") & "MB"

   End Sub

End Class








Eleкtro

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

Código (vbnet) [Seleccionar]
#Region " Form Resize Disabler "

   ' [ Form Resize Disabler ]
   '
   ' Examples:
   ' Me.EnableResizeBottom = False
   ' Me.EnableResizeTop = False

   Public Property EnableResizeTop As Boolean = True
   Public Property EnableResizeLeft As Boolean = True
   Public Property EnableResizeRight As Boolean = True
   Public Property EnableResizeBottom As Boolean = True
   Public Property EnableResizeTopLeft As Boolean = True
   Public Property EnableResizeTopRight As Boolean = True
   Public Property EnableResizeBottomLeft As Boolean = True
   Public Property EnableResizeBottomRight As Boolean = True

   Private Enum NCHitTest As Integer
       Transparent = -1
       Nowhere = 0
       Client = 1
       Caption = 2
       Left = 10
       Right = 11
       Top = 12
       TopLeft = 13
       TopRight = 14
       Bottom = 15
       BottomLeft = 16
       BottomRight = 17
       Border = 18
   End Enum

   Protected Overrides Sub WndProc(ByRef m As Message)

       MyBase.WndProc(m)

       Select Case m.Msg

           Case &H84 ' WM_NCHITTEST

               Select Case CType(m.Result, NCHitTest)

                   Case NCHitTest.Top
                       If Not Me.EnableResizeTop Then m.Result = New IntPtr(NCHitTest.Caption)

                   Case NCHitTest.Left
                       If Not Me.EnableResizeLeft Then m.Result = New IntPtr(NCHitTest.Caption)

                   Case NCHitTest.Right
                       If Not Me.EnableResizeRight Then m.Result = New IntPtr(NCHitTest.Caption)

                   Case NCHitTest.Bottom
                       If Not Me.EnableResizeBottom Then m.Result = New IntPtr(NCHitTest.Caption)

                   Case NCHitTest.TopLeft
                       If Not Me.EnableResizeTopLeft Then m.Result = New IntPtr(NCHitTest.Caption)

                   Case NCHitTest.TopRight
                       If Not Me.EnableResizeTopRight Then m.Result = New IntPtr(NCHitTest.Caption)

                   Case NCHitTest.BottomLeft
                       If Not Me.EnableResizeBottomLeft Then m.Result = New IntPtr(NCHitTest.Caption)

                   Case NCHitTest.BottomRight
                       If Not Me.EnableResizeBottomRight Then m.Result = New IntPtr(NCHitTest.Caption)

               End Select

       End Select

   End Sub

#End Region


Ejemplo de uso:

Código (vbnet) [Seleccionar]
   Private Sub Form_Shown() Handles MyBase.Shown
       Me.EnableResizeTop = False
       Me.EnableResizeBottom = False
   End Sub








Eleкtro

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



Código (vbnet) [Seleccionar]
' [ DiffLib Examples ]
'
' // By Elektro H@cker
'
' Instructions:
'
' 1. Reference the "DiffLib.dll" into the project.


#Region " DiffLib Examples "

Public Class Form1

   ReadOnly text1 As String = "This is a test of the Diff implementation, with some text that is deleted."
   ReadOnly text2 As String = "This is another test of the same implementation, with some more text."

   Private Sub Test()

       HtmlLabel1.Text = DumpDiff(New DiffLib.Diff(Of Char)(text1, text2),
                                  KnownColor.Black,
                                  KnownColor.Black,
                                  KnownColor.Black,
                                  KnownColor.Transparent,
                                  KnownColor.YellowGreen,
                                  KnownColor.Red,
                                  13)

   End Sub

   Private Function DumpDiff(ByVal changes As IEnumerable(Of DiffLib.DiffChange),
                             ByVal Forecolor As KnownColor,
                             ByVal ForecolorAdded As KnownColor,
                             ByVal ForecolorDeleted As KnownColor,
                             ByVal BackColor As KnownColor,
                             ByVal BackColorAdded As KnownColor,
                             ByVal BackColorDeleted As KnownColor,
                             Optional ByVal FontSize As Integer = 10) As String

       Dim html As New System.Text.StringBuilder()

       Dim i1 As Integer = 0
       Dim i2 As Integer = 0

       For Each change As DiffLib.DiffChange In changes

           If change.Equal Then


               html.Append(String.Format("<span style='color: {0}; background-color: {1}; font-size: {2}pt'>{3}</span>",
                                         Forecolor.ToString,
                                         BackColor.ToString,
                                         CStr(FontSize),
                                         text1.Substring(i1, change.Length1)))

           Else

               html.Append(String.Format("<span style='color: {0}; background-color: {1}; font-size: {2}pt; text-decoration: line-through;'>{3}</span>",
                                        ForecolorDeleted.ToString,
                                        BackColorDeleted.ToString,
                                         CStr(FontSize),
                                        text1.Substring(i1, change.Length1)))

               html.Append(String.Format("<span style='color: {0}; background-color: {1}; font-size: {2}pt'>{3}</span>",
                                        ForecolorAdded.ToString,
                                        BackColorAdded.ToString,
                                         CStr(FontSize),
                                        text2.Substring(i2, change.Length2)))

           End If

           i1 += change.Length1
           i2 += change.Length2

       Next change

       Return html.ToString

   End Function

End Class

#End Region








Eleкtro

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

Código (vbnet) [Seleccionar]
Imports System.Net
Imports System.Net.FtpClient
Imports System.Net.FtpClient.Extensions

#Region " FTPClient Helper "

' [ FTPClient Helper ]
'
' // By Elektro H@cker

#Region " Usage Examples "

'Public Class Form1

'    Private WithEvents UploadClient As New System.Net.WebClient()
'    Private WithEvents DownloadClient As New System.Net.WebClient()

'    Private ftp As New FTP("sitio ftp", "username", "password")

'    Private Sub Test() Handles MyBase.Shown

'        ftp.Connect()
'        ftp.CreateDirectory("/DirectoryName", True)
'        ftp.UploadFile(UploadClient, "C:\File.txt", "/DirectoryName/NewFile.txt", False)
'        ftp.DownloadFile(DownloadClient, "/DirectoryName/NewFile.txt", "c:\DownloadedFile.txt", True)

'    End Sub

'    Private Sub Client_UploadProgress(sender As System.Net.WebClient, e As System.Net.UploadProgressChangedEventArgs) _
'    Handles UploadClient.UploadProgressChanged

'        Label_Upload.Text = e.ProgressPercentage & "%"

'    End Sub

'    Private Sub Client_UploadCompleted(sender As System.Net.WebClient, e As System.Net.UploadFileCompletedEventArgs) _
'    Handles UploadClient.UploadFileCompleted

'        Label_UploadCompleted.Text = e.Result.ToString

'    End Sub

'    Private Sub Client_DownloadProgress(sender As System.Net.WebClient, e As System.Net.DownloadProgressChangedEventArgs) _
'    Handles DownloadClient.DownloadProgressChanged

'        Label_Download.Text = e.ProgressPercentage & "%"

'    End Sub

'    Private Sub Client_DownloadCompleted(sender As System.Net.WebClient, e As System.ComponentModel.AsyncCompletedEventArgs) _
'     Handles DownloadClient.DownloadFileCompleted

'        Label_DownloadCompleted.Text = "Done!"

'    End Sub

'End Class

#End Region

Public Class FTP

#Region " Variables "

   Private conn As New FtpClient

   ''' <summary>
   ''' The FTP site.
   ''' </summary>
   Private Property host As String = String.Empty

   ''' <summary>
   ''' The user name.
   ''' </summary>
   Private Property user As String = String.Empty

   ''' <summary>
   ''' The user password.
   ''' </summary>
   Private Property pass As String = String.Empty

   ' Friend m_reset As New ManualResetEvent(False) ' Use it for CallBacks

#End Region

#Region " Constructor "

   ''' <summary>
   ''' .
   ''' </summary>
   ''' <param name="host">Indicates the ftp site.</param>
   ''' <param name="user">Indicates the username.</param>
   ''' <param name="pass">Indicates the password.</param>
   Public Sub New(ByVal host As String,
                  ByVal user As String,
                  ByVal pass As String)

       If Not host.ToLower.StartsWith("ftp://") Then
           Me.host = "ftp://" & host
       Else
           Me.host = host
       End If

       If Me.host.Last = "/" Then
           Me.host = Me.host.Remove(Me.host.Length - 1)
       End If

       Me.user = user
       Me.pass = pass

       With conn
           .Host = If(host.Last = "/", host.Remove(host.Length - 1), host)
           .Credentials = New NetworkCredential(Me.user, Me.pass)
       End With

   End Sub

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Connects to server.
   ''' </summary>
   Public Sub Connect()
       conn.Connect()
   End Sub

   ''' <summary>
   ''' Disconnects from server.
   ''' </summary>
   Public Sub Disconnect()
       conn.Disconnect()
   End Sub

   ''' <summary>
   ''' Creates a directory on server.
   ''' </summary>
   ''' <param name="directorypath">Indicates the ftp directory path.</param>
   ''' <param name="force">Try to force all non-existant pieces of the path to be created.</param>
   Public Sub CreateDirectory(ByVal directorypath As String, ByVal force As Boolean)
       conn.CreateDirectory(directorypath, force)
   End Sub

   ''' <summary>
   ''' Creates a directory on server.
   ''' </summary>
   ''' <param name="directorypath">Indicates the ftp directory path.</param>
   ''' <param name="force">Try to force all non-existant pieces of the path to be created.</param>
   ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
   Public Sub DeleteDirectory(ByVal directorypath As String,
                              ByVal force As Boolean,
                              Optional ByVal FtpListOption As FtpListOption =
                              FtpListOption.AllFiles Or FtpListOption.ForceList)

       ' Remove the directory and all objects beneath it. The last parameter
       ' forces System.Net.FtpClient to use LIST -a for getting a list of objects
       ' beneath the specified directory.
       conn.DeleteDirectory(directorypath, force, FtpListOption)

   End Sub

   ''' <summary>
   ''' Deletes a file on server.
   ''' </summary>
   ''' <param name="filepath">Indicates the ftp file path.</param>
   Public Sub DeleteFile(ByVal filepath As String)
       conn.DeleteFile(filepath)
   End Sub

   ''' <summary>
   ''' Checks if a directory exist on server.
   ''' </summary>
   ''' <param name="directorypath">Indicates the ftp directory path.</param>
   Public Function DirectoryExists(ByVal directorypath As String) As Boolean
       Return conn.DirectoryExists(directorypath)
   End Function

   ''' <summary>
   ''' Executes a command on server.
   ''' </summary>
   ''' <param name="command">Indicates the command to execute on the server.</param>
   ''' <returns>Returns an object containing the server reply information.</returns>
   Public Function Execute(ByVal command As String) As FtpReply
       Return (InlineAssignHelper(New FtpReply, conn.Execute(command)))
   End Function

   ''' <summary>
   ''' Tries to execute a command on server.
   ''' </summary>
   ''' <param name="command">Indicates the command to execute on the server.</param>
   ''' <returns>Returns TRUE if command execution successfull, otherwise returns False.</returns>
   Public Function TryExecute(ByVal command As String) As Boolean
       Dim reply As FtpReply = Nothing
       Return (InlineAssignHelper(reply, conn.Execute(command))).Success
   End Function

   ''' <summary>
   ''' Checks if a file exist on server.
   ''' </summary>
   ''' <param name="filepath">Indicates the ftp file path.</param>
   ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
   Public Function FileExists(ByVal filepath As String,
                              Optional ByVal FtpListOption As FtpListOption =
                              FtpListOption.AllFiles Or FtpListOption.ForceList) As Boolean

       ' The last parameter forces System.Net.FtpClient to use LIST -a
       ' for getting a list of objects in the parent directory.
       Return conn.FileExists(filepath, FtpListOption)

   End Function

   ''' <summary>
   ''' Retrieves a checksum of the given file
   ''' using a checksumming method that the server supports, if any.
   ''' The algorithm used goes in this order:
   ''' 1. HASH command (server preferred algorithm).
   ''' 2. MD5 / XMD5 commands
   ''' 3. XSHA1 command
   ''' 4. XSHA256 command
   ''' 5. XSHA512 command
   ''' 6. XCRC command
   ''' </summary>
   ''' <param name="filepath">Indicates the ftp file path.</param>
   Public Function GetChecksum(ByVal filepath As String) As FtpHash
       Return conn.GetChecksum(filepath)
   End Function

   ''' <summary>
   ''' Gets the checksum of file on server and compare it with the checksum of local file.
   ''' </summary>
   ''' <param name="filepath">Indicates the ftp file path.</param>
   ''' <param name="localfilepath">Indicates the local disk file path.</param>
   ''' <param name="algorithm">Indicates the algorithm that should be used to verify checksums.</param>
   ''' <returns>Returns TRUE if both checksums are equal, otherwise returns False.</returns>
   Public Function VerifyChecksum(ByVal filepath As String,
                                  ByVal localfilepath As String,
                                  ByVal algorithm As FtpHashAlgorithm) As Boolean

       Dim hash As FtpHash = Nothing

       hash = conn.GetChecksum(filepath)
       ' Make sure it returned a, to the best of our knowledge, valid hash object.
       ' The commands for retrieving checksums are
       ' non-standard extensions to the protocol so we have to
       ' presume that the response was in a format understood by
       ' System.Net.FtpClient and parsed correctly.
       '
       ' In addition, there is no built-in support for verifying CRC hashes.
       ' You will need to write you own or use a third-party solution.
       If hash.IsValid AndAlso hash.Algorithm <> algorithm Then
           Return hash.Verify(localfilepath)
       Else
           Return Nothing
       End If

   End Function

   ''' <summary>
   ''' Gets the size of file.
   ''' </summary>
   ''' <param name="filepath">Indicates the ftp file path.</param>
   Public Function GetFileSize(ByVal filepath As String) As Long
       Return conn.GetFileSize(filepath)
   End Function

   ''' <summary>
   ''' Gets the currently HASH algorithm used for the HASH command on server.
   ''' </summary>
   Public Function GetHashAlgorithm() As FtpHashAlgorithm
       Return conn.GetHashAlgorithm()
   End Function

   ''' <summary>
   ''' Gets the modified time of file.
   ''' </summary>
   ''' <param name="filepath">Indicates the ftp file path.</param>
   Public Function GetModifiedTime(ByVal filepath As String) As Date
       Return conn.GetModifiedTime(filepath)
   End Function

   ''' <summary>
   ''' Returns a file/directory listing using the NLST command.
   ''' </summary>
   ''' <param name="directorypath">Indicates the ftp file path.</param>
   Public Function GetNameListing(ByVal directorypath As String) As String()
       Return conn.GetNameListing(directorypath)
   End Function

   ''' <summary>
   ''' Gets the current working directory on server.
   ''' </summary>
   Public Function GetWorkingDirectory() As String
       Return conn.GetWorkingDirectory()
   End Function

   ''' <summary>
   ''' Opens the specified file to be appended to...
   ''' </summary>
   ''' <param name="filepath">Indicates the ftp file path.</param>
   Public Function OpenAppend(ByVal filepath As String) As IO.Stream
       Return conn.OpenAppend(filepath)
   End Function

   ''' <summary>
   ''' Opens the specified file for reading.
   ''' </summary>
   ''' <param name="filepath">Indicates the ftp file path.</param>
   Public Function OpenRead(ByVal filepath As String) As IO.Stream
       Return conn.OpenRead(filepath)
   End Function

   ''' <summary>
   ''' Opens the specified file for writing.
   ''' </summary>
   ''' <param name="filepath">Indicates the ftp file path.</param>
   Public Function OpenWrite(ByVal filepath As String) As IO.Stream
       Return conn.OpenWrite(filepath)
   End Function

   ''' <summary>
   ''' Rename a file on the server.
   ''' </summary>
   ''' <param name="filepath">Indicates the ftp file path.</param>
   ''' <param name="newfilepath">Indicates the new ftp file path.</param>
   Public Sub RenameFile(ByVal filepath As String, ByVal newfilepath As String)
       If conn.FileExists(filepath) Then
           conn.Rename(filepath, newfilepath)
       Else
           Throw New Exception(filepath & " File does not exist on server.")
       End If
   End Sub

   ''' <summary>
   ''' Rename a directory on the server.
   ''' </summary>
   ''' <param name="directorypath">Indicates the ftp file path.</param>
   ''' <param name="newdirectorypath">Indicates the new ftp file path.</param>
   Public Sub RenameDirectory(ByVal directorypath As String, ByVal newdirectorypath As String)
       If conn.DirectoryExists(directorypath) Then
           conn.Rename(directorypath, newdirectorypath)
       Else
           Throw New Exception(directorypath & " Directory does not exist on server.")
       End If
   End Sub

   ''' <summary>
   ''' Tells the server wich hash algorithm to use for the HASH command.
   ''' </summary>
   ''' <param name="algorithm">Indicates the HASH algorithm.</param>
   Public Function SetHashAlgorithm(ByVal algorithm As FtpHashAlgorithm) As Boolean
       If conn.HashAlgorithms.HasFlag(algorithm) Then
           conn.SetHashAlgorithm(algorithm)
           Return True
       Else
           Return False
       End If
   End Function

   ''' <summary>
   ''' Sets the working directory on the server.
   ''' </summary>
   ''' <param name="directorypath">Indicates the ftp directory path.</param>
   Public Sub SetWorkingDirectory(ByVal directorypath As String)
       conn.SetWorkingDirectory(directorypath)
   End Sub

   ''' <summary>
   ''' Gets a directory list on the specified path.
   ''' </summary>
   ''' <param name="directorypath">Indicates the ftp directory path.</param>
   ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
   Public Function GetDirectories(ByVal directorypath As String,
                                  Optional ByVal FtpListOption As FtpListOption =
                                  FtpListOption.AllFiles) As FtpListItem()

       Return conn.GetListing(directorypath, FtpListOption).
              Where(Function(item) item.Type = FtpFileSystemObjectType.Directory)

   End Function

   ''' <summary>
   ''' Gets a file list on the specified path.
   ''' </summary>
   ''' <param name="directorypath">Indicates the ftp directory path.</param>
   ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
   Public Function GetFiles(ByVal directorypath As String,
                            Optional ByVal FtpListOption As FtpListOption =
                            FtpListOption.AllFiles) As FtpListItem()

       Return conn.GetListing(directorypath, FtpListOption).
              Where(Function(item) item.Type = FtpFileSystemObjectType.File)

   End Function

   ''' <summary>
   ''' Gets a link list on the specified path.
   ''' </summary>
   ''' <param name="directorypath">Indicates the ftp directory path.</param>
   ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
   Public Function GetLinks(ByVal directorypath As String,
                            Optional ByVal FtpListOption As FtpListOption =
                            FtpListOption.AllFiles) As FtpListItem()

       Return conn.GetListing(directorypath, FtpListOption).
              Where(Function(item) item.Type = FtpFileSystemObjectType.Link)

   End Function

   ''' <summary>
   ''' Gets a file/folder list on the specified path.
   ''' </summary>
   ''' <param name="directorypath">Indicates the ftp directory path.</param>
   ''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
   Public Function GetListing(ByVal directorypath As String,
                              Optional ByVal FtpListOption As FtpListOption =
                              FtpListOption.AllFiles) As FtpListItem()

       Return conn.GetListing(directorypath, FtpListOption)

   End Function

   ''' <summary>
   ''' Log to a console window
   ''' </summary>
   Public Sub LogToConsole()
       FtpTrace.AddListener(New ConsoleTraceListener())
       ' now use System.Net.FtpCLient as usual and the server transactions
       ' will be written to the Console window.
   End Sub

   ''' <summary>
   ''' Log to a text file
   ''' </summary>
   ''' <param name="filepath">Indicates the file where to save the log.</param>
   Public Sub LogToFile(ByVal filepath As String)
       FtpTrace.AddListener(New TextWriterTraceListener(filepath))
       ' now use System.Net.FtpCLient as usual and the server transactions
       ' will be written to the specified log file.
   End Sub

   ''' <summary>
   ''' Uploads a file from FTP.
   ''' </summary>
   ''' <param name="UploadClient">Indicates the WebClient object to upload the file.</param>
   ''' <param name="filepath">Indicates the ftp fle path.</param>
   ''' <param name="localfilepath">Specifies the local path where to save the downloaded file.</param>
   ''' <param name="Asynchronous">Indicates whether the download should be an Asynchronous operation,
   ''' to raise WebClient events.</param>
   Public Sub UploadFile(ByRef UploadClient As WebClient,
                         ByVal localfilepath As String,
                         Optional ByVal filepath As String = Nothing,
                         Optional ByVal Asynchronous As Boolean = False)

       If filepath Is Nothing Then
           filepath = Me.host & "/" & New IO.FileInfo(localfilepath).Name
       ElseIf filepath.StartsWith("/") Then
           filepath = Me.host & filepath
       Else
           filepath = Me.host & "/" & filepath
       End If

       With UploadClient
           .Credentials = New NetworkCredential(Me.user, Me.pass)
           If Asynchronous Then
               .UploadFileAsync(New Uri(filepath), "STOR", localfilepath)
           Else
               .UploadFile(New Uri(filepath), "STOR", localfilepath)
           End If
       End With
   End Sub

   ''' <summary>
   ''' Downloads a file from FTP.
   ''' </summary>
   ''' <param name="DownloadClient">Indicates the WebClient object to download the file.</param>
   ''' <param name="filepath">Indicates the ftp fle path.</param>
   ''' <param name="localfilepath">Specifies the local path where to save the downloaded file.</param>
   ''' <param name="Asynchronous">Indicates whether the download should be an Asynchronous operation,
   ''' to raise WebClient events.</param>
   Public Sub DownloadFile(ByRef DownloadClient As WebClient,
                           ByVal filepath As String,
                           ByVal localfilepath As String,
                           Optional ByVal Asynchronous As Boolean = False)

       If filepath.StartsWith("/") Then
           filepath = Me.host & filepath
       Else
           filepath = Me.host & "/" & filepath
       End If

       MsgBox(filepath)
       With DownloadClient
           .Credentials = New NetworkCredential(Me.user, Me.pass)
           If Asynchronous Then
               .DownloadFileAsync(New Uri(filepath), localfilepath)
           Else
               .DownloadFile(New Uri(filepath), localfilepath)
           End If
       End With
   End Sub

#End Region

#Region " Miscellaneous methods "

   Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
       target = value
       Return value
   End Function

#End Region

End Class

#End Region








Eleкtro

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

Código (vbnet) [Seleccionar]
#Region " Environment Variables Helper "

' [ Environment Variables Helper ]
'
' // By Elektro H@cker
'
' Examples:
' EnvironmentVariables.Add("DirFiles", "Dir /B ""*.*""", EnvironmentVariables.EnvironmentKind.CurrentUser)
' EnvironmentVariables.Remove("DirFiles", EnvironmentVariables.EnvironmentKind.CurrentUser)

Public Class EnvironmentVariables

#Region " API, Constants, Enums"

    ''' <summary>
    ''' User Environment Subkey.
    ''' </summary>
    Private Shared ReadOnly UserEnvironmentKey As String = "Environment\"

    ''' <summary>
    ''' System Environment Subkey.
    ''' </summary>
    Private Shared ReadOnly SystemEnvironmentKey As String = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment\"

    ''' <summary>
    ''' Sends the specified message to one or more windows.
    ''' </summary>
    <System.Runtime.InteropServices.
    DllImport("user32.dll", SetLastError:=True)> _
    Public Shared Function SendMessageTimeout(
                  ByVal windowHandle As IntPtr,
                  ByVal Msg As Integer,
                  ByVal wParam As IntPtr,
                  ByVal lParam As String,
                  ByVal flags As SendMessageTimeoutFlags,
                  ByVal timeout As Integer,
                  ByRef result As IntPtr
    ) As IntPtr
    End Function

    ''' <summary>
    ''' Kind of environment.
    ''' </summary>
    Public Enum EnvironmentKind As Short

        ''' <summary>
        ''' Indicates that the environment variable
        ''' should only be accesible for the current user.
        ''' </summary>
        CurrentUser = 0

        ''' <summary>
        ''' Indicates that the environment variable
        ''' should be accesible for all users.
        ''' </summary>
        System = 1

    End Enum

    ''' <summary>
    ''' Sends the specified message to one or more windows.
    ''' </summary>
    <Flags()> _
    Public Enum SendMessageTimeoutFlags As Integer

        ''' <summary>
        ''' The calling thread is not prevented from processing
        ''' other requests while waiting for the function to return.
        ''' </summary>
        SMTO_NORMAL = &H0

        ''' <summary>
        ''' Prevents the calling thread from processing any other requests until the function returns.
        ''' </summary>
        SMTO_BLOCK = &H1

        ''' <summary>
        ''' The function returns without waiting for the time-out period
        ''' to elapse if the receiving thread appears to not respond or "hangs."
        ''' </summary>
        SMTO_ABORTIFHUNG = &H2

        ''' <summary>
        ''' The function does not enforce the time-out period
        ''' as long as the receiving thread is processing messages.
        ''' </summary>
        SMTO_NOTIMEOUTIFNOTHUNG = &H8

        ''' <summary>
        ''' The function should return 0 if the receiving window is destroyed
        ''' or its owning thread dies while the message is being processed.
        ''' </summary>
        SMTO_ERRORONEXIT = &H20

    End Enum

    ''' <summary>
    ''' A message that is sent to all top-level windows when
    ''' the SystemParametersInfo function changes a system-wide setting or when policy settings have changed.
    ''' <remarks>
    ''' Applications should send WM_SETTINGCHANGE to all top-level windows when they make changes to system parameters
    ''' (This message cannot be sent directly to a window.)
    '''  To send the WM_SETTINGCHANGE message to all top-level windows,
    ''' use the SendMessageTimeout function with the hwnd parameter set to HWND_BROADCAST.
    ''' </remarks>
    ''' </summary>
    Private Const WM_SETTINGCHANGE = &H1A

    ''' <summary>
    ''' the message is sent to all top-level windows in the system,
    ''' including disabled or invisible unowned windows.
    ''' The function does not return until each window has timed out.
    ''' Therefore, the total wait time can be up to the value of uTimeout multiplied by the number of top-level windows.
    ''' </summary>
    Public Const HWND_BROADCAST = &HFFFF&

#End Region

#Region " Public methods "

    ''' <summary>
    ''' Sets an environment variable.
    ''' <remarks>If a variable already exists, will be replaced.</remarks>
    ''' </summary>
    ''' <param name="VariableName">Indicates the variable name.</param>
    ''' <param name="Value">Indicates the variable value.</param>
    ''' <param name="EnvironmentKind">Indicates the kind of environment where the variable should be added.</param>
    Public Shared Sub Add(ByVal VariableName As String,
                   ByVal Value As String,
                   ByVal EnvironmentKind As EnvironmentKind)

        Select Case EnvironmentKind

            Case EnvironmentKind.CurrentUser
                My.Computer.Registry.CurrentUser.
                    OpenSubKey(UserEnvironmentKey, True).
                    SetValue(VariableName, Value)

            Case EnvironmentKind.System
                My.Computer.Registry.LocalMachine.
                    OpenSubKey(SystemEnvironmentKey, True).
                    SetValue(VariableName, Value)

        End Select

        UpdateRegChange()

    End Sub

    ''' <summary>
    ''' Sets an environment variable.
    ''' </summary>
    ''' <param name="VariableName">Indicates the variable name.</param>
    ''' <param name="EnvironmentKind">Indicates the kind of environment from where the variable should be removed.</param>
    Public Shared Sub Remove(ByVal VariableName As String,
                      ByVal EnvironmentKind As EnvironmentKind)

        Select Case EnvironmentKind

            Case EnvironmentKind.CurrentUser
                My.Computer.Registry.CurrentUser.
                    OpenSubKey(UserEnvironmentKey, True).
                    DeleteValue(VariableName, True)

            Case EnvironmentKind.System
                My.Computer.Registry.LocalMachine.
                    OpenSubKey(SystemEnvironmentKey, True).
                    DeleteValue(VariableName, True)

        End Select

        UpdateRegChange()

    End Sub

#End Region

#Region " Private methods "

    Private Shared Sub UpdateRegChange()

        ' Update Registry Change
        SendMessageTimeout(HWND_BROADCAST,
                           WM_SETTINGCHANGE,
                           0,
                           "Environment",
                           SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,
                           1,
                           IntPtr.Zero)

    End Sub

#End Region

End Class

#End Region








Eleкtro

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 (vbnet) [Seleccionar]
Public Class Form1

    Private Sub Test()

        Dim sb As New System.Text.StringBuilder

        For Each FW In [Enum].GetValues(GetType(Campari.Software.FrameworkVersion))

            sb.AppendLine(String.Format("FW {0} Is installed?: {1}",
                                        FW.ToString.Substring(2),
                                        Campari.Software.FrameworkVersionDetection.IsInstalled(FW)))

            sb.AppendLine(String.Format("FW {0} version: {1}",
                                        FW.ToString.Substring(2),
                                        Campari.Software.FrameworkVersionDetection.GetExactVersion(FW).ToString))

            sb.Append(Environment.NewLine)

        Next

        MsgBox(sb.ToString)

    End Sub

End Class