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

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

0 Miembros y 2 Visitantes están viendo este tema.

Eleкtro

Una class con funciones para realizar todo tipo de operaciones en el Registro de Windows:

- Crear clave
- Eliminar clave
- Crear valor
- Eliminar valor
- Obtener los datos de un valor
- Exportar clave
- Importar archivo
- Saltar a clave (abrir Regedit en clave específica)
- Comprobar si un valor existe
- Comprobar si los datos de un valor están vacíos
- Copiar clave a otro lugar del registro
- Copiar valor a otro lugar del registro
- Establecer permisos de usuario para una clave

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

' [ RegEdit Functions ]
'
' // By Elektro H@cker
'
' Examples :
'
' -----------
' Create Key:
' -----------
' RegEdit.Create_Key("HKCU\Software\MyProgram")                        ' Creates "HKCU\Software\MyProgram"
' RegEdit.Create_Key("HKEY_CURRENT_USER\Software\MyProgram\Settings\") ' Creates "HKCU\Software\MyProgram\Settings"
'
' -----------
' Delete Key:
' -----------
' RegEdit.Delete_Key("HKLM\Software\7-zip")                ' Deletes the "7-zip" tree including subkeys
' RegEdit.Delete_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Deletes the "7-zip" tree including subkeys
'
' -------------
' Delete Value:
' -------------
' RegEdit.Delete_Value("HKCU\Software\7-Zip", "Lang")               ' Deletes "Lang" Value
' RegEdit.Delete_Value("HKEY_CURRENT_USER\Software\7-Zip\", "Lang") ' Deletes "Lang" Value
'
' ----------
' Get Value:
' ----------
' Dim Data As String = RegEdit.Get_Value("HKCU\Software\MyProgram", "Value name"))
' Dim Data As String = RegEdit.Get_Value("HKEY_CURRENT_USER\Software\MyProgram", "Value name"))
'
' ----------
' Set Value:
' ----------
' RegEdit.Set_Value("HKCU\Software\MyProgram", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String)               ' Create/Replace "Value Name" with "Data" as string data
' RegEdit.Set_Value("HKEY_CURRENT_USER\Software\MyProgram\", "Value name", "Data", Microsoft.Win32.RegistryValueKind.String) ' Create/Replace "Value Name" with "Data" as string data
'
' -----------
' Export Key:
' -----------
' RegEdit.Export_Key("HKLM", "C:\HKLM.reg")                  ' Export entire "HKEY_LOCAL_MACHINE" Tree to "C:\HKLM.reg" file.
' RegEdit.Export_Key("HKLM\Software\7-zip\", "C:\7-zip.reg") ' Export entire "7-zip" Tree to "C:\7-zip.reg" file.
'
' ------------
' Import File:
' ------------
' RegEdit.Import_RegFile("C:\Registry_File.reg") ' Install a registry file.
'
' ------------
' Jump To Key:
' ------------
' RegEdit.Jump_To_Key("HKLM")                               ' Opens Regedit at "HKEY_LOCAL_MACHINE" Root.
' RegEdit.Jump_To_Key("HKEY_LOCAL_MACHINE\Software\7-zip\") ' Opens Regedit at "HKEY_LOCAL_MACHINE\Software\7-zip" tree.
'
' -------------
' Exist Value?:
' -------------
' MsgBox(RegEdit.Exist_Value("HKLM\software\7-zip", "Path") ' Checks if "Path" value exist.
'
' ------------
' Exist Data?:
' ------------
' MsgBox(RegEdit.Exist_Data("HKLM\software\7-zip", "Path") ' Checks if "Path" value have empty data.
'
' ---------
' Copy Key:
' ---------
' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", "7-zip")          ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip"
' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", Nothing, "Software", "7-zip")         ' Copies "HKCU\Software\7-Zip" to "HKCU\Software\7-Zip"
' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", Nothing)          ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\"
' RegEdit.Copy_Key("HKCU", "Software", "7-Zip", "HKLM", Nothing, Nothing)             ' Copies "HKCU\Software\7-Zip" to "HKLM\"
' RegEdit.Copy_Key("HKCU", "\Software\", "\7-Zip\", "HKLM", "\Software\", "\7-zip\")  ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip"
'
' -----------
' Copy Value:
' -----------
' RegEdit.Copy_Value("HKLM\software\7-zip", "path", "HKLM\software\7-zip", "path_backup") ' Copies "Path" value with their data to "HKLM\software\7-zip" "path_backup".
'
' -----------
' Set_UserAccess_Key:
' -----------
' RegEdit.Set_UserAccess_Key("HKCU\Software\7-Zip", {RegEdit.RegUserAccess.Administrators_Full_Access})
' RegEdit.Set_UserAccess_Key("HKEY_CURRENT_USER\Software\7-Zip", {RegEdit.RegUserAccess.Administrators_Full_Access, RegEdit.RegUserAccess.Creator_Full_Access, RegEdit.RegUserAccess.System_Full_Access})

#Region " RegEdit Class "

Public Class RegEdit

   ''' <summary>
   ''' Create a new registry key.
   ''' </summary>
   Public Shared Function Create_Key(ByVal RegKey As String) As Boolean

       Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
       Dim KeyPath As String = Get_Key_Path(RegKey)

       Try
           RootKey.CreateSubKey(KeyPath)
           RootKey.Close()
           RootKey.Dispose()
           Return True
       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Delete a registry key.
   ''' </summary>
   Public Shared Function Delete_Key(ByVal RegKey As String) As Boolean

       Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
       Dim KeyPath As String = Get_Key_Path(RegKey)

       Try
           RootKey.DeleteSubKeyTree(KeyPath)
           RootKey.Close()
           RootKey.Dispose()
           Return True
       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Delete a registry key.
   ''' </summary>
   Public Shared Function Delete_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean

       Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
       Dim KeyPath As String = Get_Key_Path(RegKey)

       Try
           RootKey.OpenSubKey(KeyPath, True).DeleteValue(RegValue)
           RootKey.Close()
           RootKey.Dispose()
           Return True
       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Get the data of a registry value.
   ''' </summary>
   Public Shared Function Get_Value(ByVal RegKey As String, ByVal RegValue As String) As String

       Dim RootKey As String = Get_Root_Key(RegKey).ToString
       Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)

       Try
           Return My.Computer.Registry.GetValue(KeyPath, RegValue, Nothing)
       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try
   End Function

   ''' <summary>
   ''' Set the data of a registry value.
   ''' If the Key or value don't exist it will be created automatically.
   ''' </summary>
   Public Shared Function Set_Value(ByVal RegKey As String, _
                                    ByVal RegValue As String, _
                                    ByVal RegData As String, _
                                    ByVal RegDataType As Microsoft.Win32.RegistryValueKind) As Boolean

       Dim RootKey As String = Get_Root_Key(RegKey).ToString
       Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)

       Try
           If RegDataType = Microsoft.Win32.RegistryValueKind.Binary Then
               My.Computer.Registry.SetValue(KeyPath, RegValue, System.Text.Encoding.ASCII.GetBytes(RegData), Microsoft.Win32.RegistryValueKind.Binary)
           Else
               My.Computer.Registry.SetValue(KeyPath, RegValue, RegData, RegDataType)
           End If
           Return True
       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Export a registry key (including sub-keys) to a file.
   ''' </summary>
   Public Shared Function Export_Key(ByVal RegKey As String, ByVal OutputFile As String) As Boolean
       Dim RootKey As String = Get_Root_Key(RegKey).ToString
       Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
       If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1)

       Try
           Dim Regedit As New Process()
           Dim Regedit_Info As New ProcessStartInfo()

           Regedit_Info.FileName = "Reg.exe"
           Regedit_Info.Arguments = "Export " & """" & KeyPath & """" & " " & """" & OutputFile & """" & " /y"
           Regedit_Info.CreateNoWindow = True
           Regedit_Info.WindowStyle = ProcessWindowStyle.Hidden
           Regedit_Info.UseShellExecute = False
           Regedit.StartInfo = Regedit_Info
           Regedit.Start()
           Regedit.WaitForExit()

           If Regedit.ExitCode <> 0 Then
               Return False
           Else
               Return True
           End If

       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Import a registry file.
   ''' </summary>
   Public Shared Function Import_RegFile(ByVal RegFile As String) As Boolean

       If IO.File.Exists(RegFile) Then

           Try
               Dim Regedit As New Process()
               Dim Regedit_Info As New ProcessStartInfo()

               Regedit_Info.FileName = "Reg.exe"
               Regedit_Info.Arguments = "Import " & """" & RegFile & """"
               Regedit_Info.CreateNoWindow = True
               Regedit_Info.WindowStyle = ProcessWindowStyle.Hidden
               Regedit_Info.UseShellExecute = False
               Regedit.StartInfo = Regedit_Info
               Regedit.Start()
               Regedit.WaitForExit()

               If Regedit.ExitCode <> 0 Then
                   Return False
               Else
                   Return True
               End If

           Catch ex As Exception
               ' MsgBox(ex.Message)
               ' Throw New Exception(ex.Message)
               Return False
           End Try

       Else
           ' MsgBox("File don't exist")
           Return False

       End If

   End Function

   ''' <summary>
   ''' Open Regedit at specific key.
   ''' </summary>
   Public Shared Function Jump_To_Key(ByVal RegKey As String) As Boolean

       Dim RootKey As String = Get_Root_Key(RegKey).ToString
       Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
       If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1)

       Try
           Set_Value("HKCU\Software\Microsoft\Windows\CurrentVersion\Applets\Regedit", "LastKey", "" & KeyPath & "", Microsoft.Win32.RegistryValueKind.String)
           Process.Start("Regedit.exe")
           Return True
       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Check if a value exist.
   ''' </summary>
   Public Shared Function Exist_Value(ByVal RegKey As String, ByVal RegValue As String) As Boolean

       Dim RootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(RegKey)
       Dim KeyPath As String = Get_Key_Path(RegKey)

       Try
           If RootKey.OpenSubKey(KeyPath, False).GetValue(RegValue) = String.Empty Then
               Return False
           Else
               Return True
           End If
       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Check if a value have empty data.
   ''' </summary>
   Public Shared Function Exist_Data(ByVal RegKey As String, ByVal RegValue As String) As Boolean

       Dim RootKey As String = Get_Root_Key(RegKey).ToString
       Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)

       Try
           If My.Computer.Registry.GetValue(KeyPath, RegValue, Nothing) = Nothing Then
               Return False
           Else
               Return True
           End If
       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Copy a key tree to another location of the registry.
   ''' </summary>
   Public Shared Function Copy_Key(ByVal OldRootKey As String, _
                       ByVal OldPath As String, _
                       ByVal OldName As String, _
                       ByVal NewRootKey As String, _
                       ByVal NewPath As String, _
                       ByVal NewName As String) As Boolean

       If OldPath Is Nothing Then OldPath = ""
       If NewRootKey Is Nothing Then NewRootKey = OldRootKey
       If NewPath Is Nothing Then NewPath = ""
       If NewName Is Nothing Then NewName = ""

       If OldRootKey.EndsWith("\") Then OldRootKey = OldRootKey.Substring(0, OldRootKey.Length - 1)
       If NewRootKey.EndsWith("\") Then NewRootKey = NewRootKey.Substring(0, NewRootKey.Length - 1)

       If OldPath.StartsWith("\") Then OldPath = OldPath.Substring(1, OldPath.Length - 1)
       If OldPath.EndsWith("\") Then OldPath = OldPath.Substring(0, OldPath.Length - 1)
       If NewPath.StartsWith("\") Then NewPath = NewPath.Substring(1, NewPath.Length - 1)
       If NewPath.EndsWith("\") Then NewPath = NewPath.Substring(0, NewPath.Length - 1)

       If OldName.StartsWith("\") Then OldName = OldName.Substring(1, OldName.Length - 1)
       If OldName.EndsWith("\") Then OldName = OldName.Substring(0, OldName.Length - 1)
       If NewName.StartsWith("\") Then NewName = NewName.Substring(1, NewName.Length - 1)
       If NewName.EndsWith("\") Then NewName = NewName.Substring(0, NewName.Length - 1)

       Dim OrigRootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(OldRootKey)
       Dim DestRootKey As Microsoft.Win32.RegistryKey = Get_Root_Key(NewRootKey)

       Dim oldkey As Microsoft.Win32.RegistryKey = OrigRootKey.OpenSubKey(OldPath + "\" + OldName, True)
       Dim newkey As Microsoft.Win32.RegistryKey = DestRootKey.OpenSubKey(NewPath, True).CreateSubKey(NewName)
       Reg_Copy_SubKeys(oldkey, newkey)
       Return True
   End Function

   Private Shared Sub Reg_Copy_SubKeys(OrigKey As Microsoft.Win32.RegistryKey, DestKey As Microsoft.Win32.RegistryKey)

       Dim ValueNames As String() = OrigKey.GetValueNames()
       Dim SubKeyNames As String() = OrigKey.GetSubKeyNames()

       For i As Integer = 0 To ValueNames.Length - 1
           Application.DoEvents()
           DestKey.SetValue(ValueNames(i), OrigKey.GetValue(ValueNames(i)))
       Next

       For i As Integer = 0 To SubKeyNames.Length - 1
           Application.DoEvents()
           Reg_Copy_SubKeys(OrigKey.OpenSubKey(SubKeyNames(i), True), DestKey.CreateSubKey(SubKeyNames(i)))
       Next

   End Sub

   ''' <summary>
   ''' Copy a value with their data to another location of the registry.
   ''' If the Key don't exist it will be created automatically.
   ''' </summary>
   Public Shared Function Copy_Value(ByVal RegKey As String, ByVal RegValue As String, _
                                     ByVal NewRegKey As String, ByVal NewRegValue As String) As Boolean

       Dim OldRootKey As String = Get_Root_Key(RegKey).ToString
       Dim OldKeyPath As String = OldRootKey & "\" & Get_Key_Path(RegKey)

       Dim NewRootKey As String = Get_Root_Key(NewRegKey).ToString
       Dim NewKeyPath As String = NewRootKey & "\" & Get_Key_Path(NewRegKey)

       Dim RegData = Get_Value(OldKeyPath, RegValue)

       Try
           Set_Value(NewKeyPath, NewRegValue, RegData, Microsoft.Win32.RegistryValueKind.Unknown)
           Return True
       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Valid User identifiers for Regini.exe command.
   ''' </summary>
   Public Enum RegUserAccess As Short
       Administrators_Full_Access = 1
       Administrators_Read_Access = 2
       Administrators_Read_and_Write_Access = 3
       Administrators_Read_Write_and_Delete_Access4
       Administrators_Read_Write_and_Execute_Access = 20
       Creator_Full_Access = 5
       Creator_Read_and_Write_Access = 6
       Interactive_User_Full_Access = 21
       Interactive_User_Read_and_Write_Access = 22
       Interactive_User_Read_Write_and_Delete_Access = 23
       Power_Users_Full_Access = 11
       Power_Users_Read_and_Write_Access = 12
       Power_Users_Read_Write_and_Delete_Access = 13
       System_Full_Access = 17
       System_Operators_Full_Access = 14
       System_Operators_Read_and_Write_Access = 15
       System_Operators_Read_Write_and_Delete_Access = 16
       System_Read_Access = 19
       System_Read_and_Write_Access = 18
       World_Full_Access = 7
       World_Read_Access = 8
       World_Read_and_Write_Access = 9
       World_Read_Write_and_Delete_Access = 10
   End Enum

   ''' <summary>
   ''' Modify the User permissions of a registry key.
   ''' </summary>
   Public Shared Function Set_UserAccess_Key(ByVal RegKey As String, ByVal RegUserAccess() As RegUserAccess) As Boolean

       Dim PermissionString As String = Nothing
       Dim RootKey As String = Get_Root_Key(RegKey).ToString

       Dim KeyPath As String = RootKey & "\" & Get_Key_Path(RegKey)
       If KeyPath.EndsWith("\") Then KeyPath = KeyPath.Substring(0, KeyPath.Length - 1)

       For Each user In RegUserAccess
           Application.DoEvents()
           PermissionString += " " & user
       Next

       PermissionString = "[" & PermissionString & "]"
       PermissionString = PermissionString.Replace("[ ", "[")

       Try

           Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "Regini.ini", False, System.Text.Encoding.ASCII)
               TextFile.WriteLine("""" & KeyPath & """" & " " & PermissionString)
           End Using

           Dim Regini As New Process()
           Dim Regini_Info As New ProcessStartInfo()

           Regini_Info.FileName = "Regini.exe"


           MsgBox(PermissionString)
           MsgBox("Regini.exe " & """" & System.IO.Path.GetTempPath() & "Regini.ini" & """")


           Regini_Info.Arguments = """" & System.IO.Path.GetTempPath() & "Regini.ini" & """"
           Regini_Info.CreateNoWindow = True
           Regini_Info.WindowStyle = ProcessWindowStyle.Hidden
           Regini_Info.UseShellExecute = False
           Regini.StartInfo = Regini_Info
           Regini.Start()
           Regini.WaitForExit()

           If Regini.ExitCode <> 0 Then
               Return False
           Else
               Return True
           End If

       Catch ex As Exception
           ' MsgBox(ex.Message)
           ' Throw New Exception(ex.Message)
           Return False
       End Try

   End Function

   ' Returns the RootKey formatted
   Private Shared Function Get_Root_Key(ByVal RegKey As String) As Microsoft.Win32.RegistryKey
       Select Case RegKey.ToUpper.Split("\").First
           Case "HKCR", "HKEY_CLASSES_ROOT" : Return Microsoft.Win32.Registry.ClassesRoot
           Case "HKCC", "HKEY_CURRENT_CONFIG" : Return Microsoft.Win32.Registry.CurrentConfig
           Case "HKCU", "HKEY_CURRENT_USER" : Return Microsoft.Win32.Registry.CurrentUser
           Case "HKLM", "HKEY_LOCAL_MACHINE" : Return Microsoft.Win32.Registry.LocalMachine
           Case "HKEY_PERFORMANCE_DATA" : Return Microsoft.Win32.Registry.PerformanceData
           Case Else : Return Nothing
       End Select
   End Function

   ' Returns the KeyPath formatted
   Private Shared Function Get_Key_Path(ByVal RegKey As String) As String
       Dim KeyPath As String = String.Empty
       For i As Integer = 1 To RegKey.Split("\").Length - 1
           Application.DoEvents()
           KeyPath += RegKey.Split("\")(i) & "\"
       Next

       If Not KeyPath.Contains("\") Then KeyPath = KeyPath & "\"
       KeyPath = KeyPath.Substring(0, KeyPath.LastIndexOf("\"))

       Return KeyPath
   End Function

End Class

#End Region

#End Region








TrashAmbishion

El codigo de agregar un usuario en el sistema, lo tienes incluido aqui ?

Barbarísimo estos codes, este POST es para codes hechos por uno o se puede publicar un code que me haya encontrado, salu2

thx

Eleкtro

#112
Cita de: TrashAmbishion en  8 Mayo 2013, 16:20 PMEl codigo de agregar un usuario en el sistema, lo tienes incluido aqui ?
¿Incluido donde?, ¿en el archivo del recopilatorio comprimido?, a que te refieres, el código lo tienes en la página 7.

Cita de: TrashAmbishion en  8 Mayo 2013, 16:20 PMBarbarísimo estos codes, este POST es para codes hechos por uno o se puede publicar un code que me haya encontrado, salu2
No hay reglas, puedes publicar tanto código própio como ajeno,
lo importante que hay que tener en cuenta es que séa código re-usable y no código hardcodeado.

un saludo!

EDITO:

Cita de: TrashAmbishion en  8 Mayo 2013, 15:58 PM
Man tu tienes todos los codes que publicas alli dentro del compactado ??
Si, todos los codes que yo he publicado es porque he necesitado usarlos, y me guardo una copia que puedes encontrar en el post principal.








Eleкtro

¡ PACK DE SNIPPETS ACTUALIZADO EN EL POST PRINCIPAL !

Ya puedes descargar la colección completa de 290 snippets útiles.

PD: Y no te olvides de ser generoso compartiendo tu conocimiento con los demás en este post...

http://elektrostudios.tk/Snippets.zip








Eleкtro

Con esta Class pueden manejar la aplicación BoxedAppPacker en tiempo de ejecución para empaquetar otros proyectos .NET (u otro tipo de executables) para virtualizarlos.
PD: Se necesita la aplicación BoxedAppPacker v3.XXX (versión de consola), la class no usa el SDK.

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

' [ BoxedAppPacker Functions ]
'
' // By Elektro H@cker
'
' Instructions:
' 1. Add the "BoxedAppPackerConsole.exe" to the project
' 2. Add the "BoxedAppPacker Class" Class to the project
'
' Examples:
'
' -----------------
' Pack Single File:
' -----------------
' BoxedAppPacker.Pack_Single_File("C:\Windows\Explorer.exe", "C:\Virtual Explorer.exe")
' BoxedAppPacker.Pack_Single_File("C:\Windows\Explorer.exe", "C:\Virtual Explorer.exe", True, True, True, True, True, BoxedAppPacker.BoxedAppPackerVariables.ExeDir)
'
' ---------------------------------
' Pack File And Include More Files:
' ---------------------------------
' BoxedAppPacker.Pack_File_And_Include_More_Files("C:\Windows\Explorer.exe", {"C:\Windows\system32\shell32.dll", "C:\Windows\system32\notepad.exe"}, "C:\Virtual Explorer.exe", True, True, True)


#Region " BoxedAppPacker Class "

Public Class BoxedAppPacker

   ''' <summary>
   ''' The BoxedAppPackerConsole.exe location.
   ''' </summary>
   Public Shared BoxedAppPacker_Location As String = ".\BoxedAppPackerConsole.exe"

   ''' <summary>
   ''' Boxed App Packer Variables To Override CommandLine.
   ''' </summary>
   Public Enum BoxedAppPackerVariables
       ExeDir ' a directory that contains the packed exe.
       CurDir ' current directory .
       ProgramFiles ' ProgramFiles environment variable.
       Temp ' Temp environment variable.
       BoxedAppVar_ExeFileName ' exe's file name (for example, "notepad.exe")
       BoxedAppVar_ExeFileExtension ' exe's file extension (for example, "exe")
       BoxedAppVar_ExeFileNameWithoutExtension ' exe's file name without extension (for example, "notepad")
       BoxedAppVar_ExeFullPath ' exe's full path (for example, "C_\notepad.exe")
       BoxedAppVar_OldCmdLine ' a command line specified when the packed exe started, you can use it to add additional arguments, for example: <BoxedAppVar:OldCmdLine> /NewSwitch
       BoxedAppVar_OldArgs ' a command line specified when the packed exe started without the exe path, for example "<BoxedAppVar:ExeFullPath>" /C virtual.cmd <BoxedAppVar:OldArgs>, Usage: packed.exe Arg1 Arg2, It works as: original.exe /C virtual.cmd Arg1 Arg2
   End Enum

   ''' <summary>
   ''' Virtualize a single executable.
   ''' </summary>
   Public Shared Function Pack_Single_File(ByVal File As String, ByVal OutputFile As String, _
                                   Optional ByVal Make_All_File_And_Registry_Changes_Virtual As Boolean = True, _
                                   Optional ByVal Hide_Virtual_Files_From_File_Dialog As Boolean = True, _
                                   Optional ByVal Share_Virtual_Environment_With_Child_Processes As Boolean = False, _
                                   Optional ByVal Enable_Virtual_Registry As Boolean = True, _
                                   Optional ByVal Enable_CommandLine_Arguments As Boolean = True, _
                                   Optional ByVal CommandLine_Variable As BoxedAppPackerVariables = BoxedAppPackerVariables.ExeDir
                                   ) As Boolean

       If Not Check_InputExecutable(File) Then Return False

       Dim CommandLine_Variable_Formatted As String = CommandLine_Variable.ToString.Replace("_", ":")

       Dim BoxedProject_Options_Section As String = "<project project_version=""2"" src=""" _
                                                    & File & _
                                                    """ dest=""" _
                                                    & OutputFile & _
                                                    """ cmd_line_overridden=""" _
                                                    & Enable_CommandLine_Arguments & _
                                                    """ cmd_args=""&lt;" _
                                                    & CommandLine_Variable_Formatted & _
                                                    "&gt;"" share_virtual_environment_with_child_processes=""" _
                                                    & Share_Virtual_Environment_With_Child_Processes & _
                                                    """ enable_debug_log=""false"" " & _
                                                    "enable_virtual_registry=""" _
                                                    & Enable_Virtual_Registry & _
                                                    """ hide_virtual_files_from_file_dialog=""" _
                                                    & Hide_Virtual_Files_From_File_Dialog & _
                                                    """ all_changes_are_virtual=""" _
                                                    & Make_All_File_And_Registry_Changes_Virtual & """>"

       Dim BoxedProject_File_Section As String = <a><![CDATA[

 <files>
   <file source_path="" name="&lt;ExeDir&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
     <files/>
   </file>
   <file source_path="" name="&lt;SystemRoot&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
     <files>
       <file source_path="" name="System32" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
         <files/>
       </file>
     </files>
   </file>
 </files>
]]></a>.Value

       Dim BoxedProject_Registry_Section As String = <a><![CDATA[
 <registry>
   <keys>
     <key name="HKEY_CLASSES_ROOT" virtual="false" virtually_deleted="false">
       <values/>
       <keys/>
     </key>
     <key name="HKEY_CURRENT_CONFIG" virtual="false" virtually_deleted="false">
       <values/>
       <keys/>
     </key>
     <key name="HKEY_CURRENT_USER" virtual="false" virtually_deleted="false">
       <values/>
       <keys/>
     </key>
     <key name="HKEY_LOCAL_MACHINE" virtual="false" virtually_deleted="false">
       <values/>
       <keys/>
     </key>
     <key name="HKEY_USERS" virtual="false" virtually_deleted="false">
       <values/>
       <keys/>
     </key>
   </keys>
 </registry>
</project>
]]></a>.Value

       Try
           Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", False, System.Text.Encoding.ASCII)
               TextFile.WriteLine(BoxedProject_Options_Section)
           End Using

           Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", True, System.Text.Encoding.ASCII)
               TextFile.WriteLine(BoxedProject_File_Section)
               TextFile.WriteLine(BoxedProject_Registry_Section)
           End Using

           Dim BoxedAppPacker_Console As New Process()
           Dim BoxedAppPacker_Console_Info As New ProcessStartInfo()

           BoxedAppPacker_Console_Info.FileName = BoxedAppPacker_Location
           BoxedAppPacker_Console_Info.Arguments = """" & System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj" & """"
           BoxedAppPacker_Console_Info.CreateNoWindow = True
           BoxedAppPacker_Console_Info.WindowStyle = ProcessWindowStyle.Hidden
           BoxedAppPacker_Console_Info.UseShellExecute = False
           BoxedAppPacker_Console.StartInfo = BoxedAppPacker_Console_Info
           BoxedAppPacker_Console.Start()
           BoxedAppPacker_Console.WaitForExit()

           If BoxedAppPacker_Console.ExitCode <> 0 Then
               Return False
           Else
               Return True
           End If
       Catch ex As Exception
           ' MsgBox(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Virtualize a executable and include more files.
   ''' </summary>
   Public Shared Function Pack_File_And_Include_More_Files(ByVal File As String, ByVal SubFiles() As String, ByVal OutputFile As String, _
                               Optional ByVal Make_All_File_And_Registry_Changes_Virtual As Boolean = True, _
                               Optional ByVal Hide_Virtual_Files_From_File_Dialog As Boolean = True, _
                               Optional ByVal Share_Virtual_Environment_With_Child_Processes As Boolean = False, _
                               Optional ByVal Enable_Virtual_Registry As Boolean = True, _
                               Optional ByVal Enable_CommandLine_Arguments As Boolean = True, _
                               Optional ByVal CommandLine_Variable As BoxedAppPackerVariables = BoxedAppPackerVariables.ExeDir
                               ) As Boolean

       If Not Check_InputExecutable(File) Then Return False

       Dim CommandLine_Variable_Formatted As String = CommandLine_Variable.ToString.Replace("_", ":")

       Dim BoxedProject_Options_Section As String = "<project project_version=""2"" src=""" _
                                                    & File & _
                                                    """ dest=""" _
                                                    & OutputFile & _
                                                    """ cmd_line_overridden=""" _
                                                    & Enable_CommandLine_Arguments & _
                                                    """ cmd_args=""&lt;" _
                                                    & CommandLine_Variable_Formatted & _
                                                    "&gt;"" share_virtual_environment_with_child_processes=""" _
                                                    & Share_Virtual_Environment_With_Child_Processes & _
                                                    """ enable_debug_log=""false"" " & _
                                                    "enable_virtual_registry=""" _
                                                    & Enable_Virtual_Registry & _
                                                    """ hide_virtual_files_from_file_dialog=""" _
                                                    & Hide_Virtual_Files_From_File_Dialog & _
                                                    """ all_changes_are_virtual=""" _
                                                    & Make_All_File_And_Registry_Changes_Virtual & """>"

       ' Generate File Section Start
       Dim BoxedProject_File_Section_Start As String = <a><![CDATA[

 <files>
   <file source_path="" name="&lt;ExeDir&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
     <files>
]]></a>.Value

       ' Generate SubFiles Tags Section
       Dim FileCount As Int16 = 0
       Dim SubFile_Tag As String = Nothing

       For SubFile As Integer = 1 To SubFiles.Count
           Application.DoEvents()
           FileCount += 1

           If FileCount = 1 Then
               SubFile_Tag += <a><![CDATA[
       <file source_path="]]></a>.Value & SubFiles(FileCount - 1) & <a><![CDATA[" name="]]></a>.Value & SubFiles(FileCount - 1).Split("\").Last & <a><![CDATA[" virtual="true" virtually_deleted="false" dir="false" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="/RegServer" register_as_typelib="false">
         <files/>
]]></a>.Value
           Else
               SubFile_Tag += <a><![CDATA[
       </file>
       <file source_path="]]></a>.Value & SubFiles(FileCount - 1) & <a><![CDATA[" name="]]></a>.Value & SubFiles(FileCount - 1).Split("\").Last & <a><![CDATA[" virtual="true" virtually_deleted="false" dir="false" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="/RegServer" register_as_typelib="false">
         <files/>
]]></a>.Value
           End If

       Next

       ' Generate File Section End
       Dim BoxedProject_File_Section_End As String = <a><![CDATA[
       </file>
     </files>
   </file>
   <file source_path="" name="&lt;SystemRoot&gt;" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
     <files>
       <file source_path="" name="System32" virtual="false" virtually_deleted="false" dir="true" plugin="false" register_as_com_library="false" register_as_com_server="false" com_server_reg_cmd_line_args="" register_as_typelib="false">
         <files/>
       </file>
     </files>
   </file>
 </files>
]]></a>.Value

       ' Generate Registry Section
       Dim BoxedProject_Registry_Section As String = <a><![CDATA[
 <registry>
   <keys>
     <key name="HKEY_CLASSES_ROOT" virtual="false" virtually_deleted="false">
       <values/>
       <keys/>
     </key>
     <key name="HKEY_CURRENT_CONFIG" virtual="false" virtually_deleted="false">
       <values/>
       <keys/>
     </key>
     <key name="HKEY_CURRENT_USER" virtual="false" virtually_deleted="false">
       <values/>
       <keys/>
     </key>
     <key name="HKEY_LOCAL_MACHINE" virtual="false" virtually_deleted="false">
       <values/>
       <keys/>
     </key>
     <key name="HKEY_USERS" virtual="false" virtually_deleted="false">
       <values/>
       <keys/>
     </key>
   </keys>
 </registry>
</project>
]]></a>.Value

       Try

           Using TextFile As New IO.StreamWriter(System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj", False, System.Text.Encoding.ASCII)
               TextFile.WriteLine(BoxedProject_Options_Section)
               TextFile.WriteLine(BoxedProject_File_Section_Start)
               TextFile.WriteLine(SubFile_Tag)
               TextFile.WriteLine(BoxedProject_File_Section_End)
               TextFile.WriteLine(BoxedProject_Registry_Section)
           End Using

           Dim BoxedAppPacker_Console As New Process()
           Dim BoxedAppPacker_Console_Info As New ProcessStartInfo()

           BoxedAppPacker_Console_Info.FileName = BoxedAppPacker_Location
           BoxedAppPacker_Console_Info.Arguments = """" & System.IO.Path.GetTempPath() & "BoxedAppPacker.boxedappproj" & """"
           BoxedAppPacker_Console_Info.CreateNoWindow = True
           BoxedAppPacker_Console_Info.WindowStyle = ProcessWindowStyle.Hidden
           BoxedAppPacker_Console_Info.UseShellExecute = False
           BoxedAppPacker_Console.StartInfo = BoxedAppPacker_Console_Info
           BoxedAppPacker_Console.Start()
           BoxedAppPacker_Console.WaitForExit()

           If BoxedAppPacker_Console.ExitCode <> 0 Then
               Return False
           Else
               Return True
           End If
       Catch ex As Exception
           ' MsgBox(ex.Message)
           Return False
       End Try

   End Function

   ' Checks if InputFile exist and also is a executable.
   Private Shared Function Check_InputExecutable(ByVal File As String) As Boolean
       If Not IO.File.Exists(File) Then
           MsgBox("File don't exist.")
           Return False
       End If
       If Not File.ToLower.EndsWith(".exe") Then
           MsgBox("Not a valid executable file.")
           Return False
       End If
       Return True
   End Function

End Class

#End Region

#End Region








Eleкtro

Hacer Ping a una máquina:

Código (vbnet) [Seleccionar]
    #Region " Ping "
     
       ' [ Ping Function ]
       '
       ' // By Elektro H@cker
       '
       ' Examples :
       ' MsgBox(Ping("www.google.com"))
       ' MsgBox(Ping("www.google.com", 500))
       ' MsgBox(Ping("www.google.com", 500, New Byte(128) {}, False))
       ' MsgBox(Ping("www.google.com", 500, System.Text.Encoding.ASCII.GetBytes("Hello"), True))
       ' For X As Int32 = 1 To 10 : If Not Ping("www.google.com", 1000) Then : MsgBox("Ping try " & X & " failed") : End If : Next : MsgBox("Ping successfully")
     
       Public Function Ping(ByVal Address As String, _
                              Optional ByVal TimeOut As Int64 = 200, _
                              Optional ByVal BufferData As Byte() = Nothing, _
                              Optional ByVal FragmentData As Boolean = False, _
                              Optional ByVal TimeToLive As Int64 = 128) As Boolean
     
           Dim PingSender As New System.Net.NetworkInformation.Ping()
           Dim PingOptions As New System.Net.NetworkInformation.PingOptions()
     
           If FragmentData Then PingOptions.DontFragment = False Else PingOptions.DontFragment = True
           If BufferData Is Nothing Then BufferData = New Byte(31) {} ' Sets a BufferSize of 32 Bytes
           PingOptions.Ttl = TimeToLive
     
           Dim Reply As System.Net.NetworkInformation.PingReply = PingSender.Send(Address, TimeOut, BufferData, PingOptions)
     
           If Reply.Status = System.Net.NetworkInformation.IPStatus.Success Then
               ' MsgBox("Address: " & Reply.Address.ToString)
               ' MsgBox("RoundTrip time: " & Reply.RoundtripTime)
               ' MsgBox("Time to live: " & Reply.Options.Ttl)
               ' MsgBox("Buffer size: " & Reply.Buffer.Length)
               Return True
           Else
               Return False
           End If
     
       End Function
     
    #End Region








Eleкtro

#116

Devuelve la dirección IP de un Host

Código (vbnet) [Seleccionar]
#Region " HostName To IP "

   ' [ HostName To IP Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   '
   ' MsgBox(HostName_To_IP("www.google.com")) ' Result: 173.194.41.6

   Public Function HostName_To_IP(ByVal HotsName As String) As String
       Return System.Net.Dns.GetHostEntry(HotsName).AddressList(1).ToString()
   End Function

#End Region





Devuelve el Hostname de una IP

Código (vbnet) [Seleccionar]
#Region " IP To HostName "

   ' [ IP To HostName Function ]
   '
   ' // By Elektro H@cker
   '
   ' Examples :
   '
   ' MsgBox(IP_To_HostName("173.194.41.6")) ' Result: mad01s14-in-f6.1e100.net

   Public Function IP_To_HostName(ByVal IP As String) As String
       Return system.net.Dns.GetHostEntry(IP).HostName.ToString
   End Function

#End Region







Valida si un nombre de archivo o ruta contiene caracteres no permitidos por Windows

(Este snippet lo posteé hace tiempo pero tenía varios fallos, los he corregido.)

Código (vbnet) [Seleccionar]
#Region " Validate Windows FileName "

   ' [ Validate Windows FileName Function ]
   '
   ' Examples :
   ' MsgBox(Validate_Windows_FileName("C:\Test.txt"))  ' Result: True
   ' MsgBox(Validate_Windows_FileName("C:\Te|st.txt")) ' Result: False

   Private Function Validate_Windows_FileName(ByRef FileName As String)
       Dim Directory As String = Nothing
       Dim File As String = Nothing

       Try
           Directory = FileName.Substring(0, FileName.LastIndexOf("\")) & "\"
           File = FileName.Split("\").Last
       Catch
           If Directory Is Nothing Then File = FileName
       End Try

       If Directory Is Nothing AndAlso File Is Nothing Then Return False

       If Not Directory Is Nothing Then
           For Each InvalidCharacter As Char In IO.Path.GetInvalidPathChars
               If Directory.Contains(InvalidCharacter) Then
                   ' MsgBox(InvalidCharacter)
                   Return False
               End If
           Next
       End If

       If Not File Is Nothing Then
           For Each InvalidCharacter As Char In IO.Path.GetInvalidFileNameChars
               If File.Contains(InvalidCharacter) Then
                   ' MsgBox(InvalidCharacter)
                   Return False
               End If
           Next
       End If

       Return True ' FileName is valid
   End Function

#End Region








Eleкtro

Una class para combinar ejecutable de .NET con dependencias (dll's) en tiempo de ejecución...

Se necesita la aplicación IlMerge

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

' [ IlMerge Functions ]
'
' // By Elektro H@cker
'
' Instructions:
' 1. Add the "IlMerge.exe" to the project
' 2. Add the "IlMerge" Class to the project
'
' Examples:
' IlMerge.Merge({"C:\Application.exe", "C:\Dependency.dll"}, "C:\Merged.exe")
' MsgBox(IlMerge.Merge({"C:\Application.exe", "C:\Dependency.dll"}, "C:\Merged.exe"))


#Region " IlMerge class "

Public Class IlMerge

   ''' <summary>
   ''' Set the location of IlMerge executable [Default: ".\IlMerge.exe"].
   ''' </summary>
   Public Shared IlMerge_Location As String = ".\IlMerge.exe"
   ''' <summary>
   ''' Set the location of IlMerge log file [Default: ".\IlMerge.log"].
   ''' </summary>
   Public Shared IlMerge_Log_Location As String = IlMerge_Location.Substring(0, IlMerge_Location.Length - 4) & ".log"

   ''' <summary>
   ''' Merge
   ''' </summary>
   Public Shared Function Merge(ByVal InputFiles As String(), ByVal OutputFile As String) As Boolean

       Dim FilesString As String = Nothing
       For Each File In InputFiles : FilesString += """" & File & """" & " " : Next

       Try : IO.File.Delete(IlMerge_Log_Location) : Catch : End Try ' Deletes old log if exist

       Try
           Dim ResHacker As New Process()
           Dim ResHacker_Info As New ProcessStartInfo()

           ResHacker_Info.FileName = IlMerge_Location
           ResHacker_Info.Arguments = "/ndebug /log:" & """" & IlMerge_Log_Location & """" & " /out:" & """" & OutputFile & """" & " " & FilesString
           ResHacker_Info.UseShellExecute = False
           ResHacker.StartInfo = ResHacker_Info
           ResHacker.Start()
           ResHacker.WaitForExit()

           Try : IO.File.Delete(OutputFile.Substring(0, OutputFile.Length - 4) & ".pdb") : Catch : End Try ' Deletes Debug Generated File
           Return Check_Last_Error()

       Catch ex As Exception
           MsgBox(ex.Message)
           Return False
       End Try

   End Function

   ''' <summary>
   ''' Return the last operation error if any [False = ERROR, True = Ok].
   ''' </summary>
   Private Shared Function Check_Last_Error()

       Try
           Dim Line As String = Nothing
           Dim Text As IO.StreamReader = IO.File.OpenText(IlMerge_Log_Location)

           Do Until Text.EndOfStream
               Line = Text.ReadLine()
               If Line.ToString.StartsWith("An exception occurred") Then
                   Process.Start(IlMerge_Log_Location)
                   Return False
               End If
           Loop

           Text.Close()
           Text.Dispose()
           Return True
       Catch ex As Exception
           MsgBox(ex.Message)
           Return False
       End Try

   End Function

End Class

#End Region

#End Region








Eleкtro

Comprobar si una imagen contiene cierto color.

Esta función me ha costado la vida conseguirla, ya la pueden guardar bien xD...


Código (vbnet) [Seleccionar]
  Private Function Image_Has_Color(ByVal image As Image, ByVal color As Color) As Boolean

       Using Bitmap_Image = New Bitmap(image.Width, image.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)

           Graphics.FromImage(Bitmap_Image).DrawImage(image, 0, 0)

           Dim Bitmap_Data = Bitmap_Image.LockBits(New Rectangle(0, 0, Bitmap_Image.Width, Bitmap_Image.Height), System.Drawing.Imaging.ImageLockMode.[ReadOnly], Bitmap_Image.PixelFormat)
           Dim Bitmap_Pointer As IntPtr = Bitmap_Data.Scan0

           Dim Pixel_Color As Int32
           Dim Result As Boolean = False

           For i = 0 To Bitmap_Data.Height * Bitmap_Data.Width - 1

               Pixel_Color = System.Runtime.InteropServices.Marshal.ReadInt32(Bitmap_Pointer, i * 4)

               If (Pixel_Color And &HFF000000) <> 0 AndAlso (Pixel_Color And &HFFFFFF) = (color.ToArgb() And &HFFFFFF) Then
                   Result = True
                   Exit For
               End If

           Next

           Bitmap_Image.UnlockBits(Bitmap_Data)
           Return Result

       End Using

   End Function


Ejemplo:
Código (vbnet) [Seleccionar]

   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
       MsgBox(Image_Has_Color(System.Drawing.Image.FromFile("C:\imagen.jpg"), Color.FromArgb(240, 240, 240)))
   End Sub








Eleкtro

#119
Devuelve una lista con todos los valores de una enumeración

Código (vbnet) [Seleccionar]
   #Region " Get Enum Values "
   
      ' [ Get Enum Values Function ]
      '
      ' // By Elektro H@cker
      '
      ' Examples :
      ' For Each value In Get_Enum_Values(Of KnownColor)() : MsgBox(value) : Next
   
   Private Function Get_Enum_Values(Of T)() As List(Of String)
       Dim ValueList As New List(Of String)
       For Each value In System.[Enum].GetValues(GetType(T)) : ValueList.Add(value.ToString) : Next
       Return ValueList
   End Function
   
   #End Region







Como hacer un Loop sobre todos los colores conocidos:

Código (vbnet) [Seleccionar]
       For Each col In System.[Enum].GetValues(GetType(KnownColor))
           Dim mycolor As Color = Color.FromKnownColor(col)
           MsgBox(mycolor.ToString)
            MsgBox(mycolor.R)
            MsgBox(mycolor.G)
            MsgBox(mycolor.B)
       Next