|
9301
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 7 Mayo 2013, 14:55 pm
|
Ejemplo de un comentário de sumário (o Method description): Public Class MyClass ''' <summary> ''' A description for this variable [Default: False]. ''' </summary> Public Shared MyVariable As Boolean = False End class
Ejemplo de un Select case para comparar 2 o más strings (el equivalente al OR): Select Case Variable.ToUpper Case "HELLO" MsgBox("You said HELLO.") Case "BYE", "HASTALAVISTA" MsgBox("You said BYE or HASTALAVISTA.") Case Else MsgBox("You said nothing.") End Select
Concatenar texto en varios colores en la consola #Region " Write Color Text " ' [ Write Color Text ] ' ' // By Elektro H@cker ' ' Examples: ' Write_Color_Text("TestString A", ConsoleColor.Cyan) ' Write_Color_Text(" + ", ConsoleColor.Green) ' Write_Color_Text("TestString B" & vbNewLine, ConsoleColor.White, ConsoleColor.DarkRed) ' Console.ReadLine() Private Sub Write_Color_Text(ByVal Text As String, _ Optional ByVal ForeColor As System.ConsoleColor = ConsoleColor.White, _ Optional ByVal BackColor As System.ConsoleColor = ConsoleColor.Black) Console.ForegroundColor = ForeColor Console.BackgroundColor = BackColor Console.Write(Text) Console.ForegroundColor = ConsoleColor.White Console.BackgroundColor = ConsoleColor.Black End Sub #End Region
Añade la aplicación actual al inicio de sesión de windows: #Region " Add Application To Startup " ' [ Add Application To Startup Function ] ' ' // By Elektro H@cker ' ' Examples : ' Add_Application_To_Startup(Startup_User.All_Users) ' Add_Application_To_Startup(Startup_User.Current_User) ' Add_Application_To_Startup(Startup_User.Current_User, "Application Name", """C:\ApplicationPath.exe""" & " -Arguments") Public Enum Startup_User Current_User All_Users End Enum Private Function Add_Application_To_Startup(ByVal Startup_User As Startup_User, _ Optional ByVal Application_Name As String = Nothing, _ Optional ByVal Application_Path As String = Nothing) As Boolean If Application_Name Is Nothing Then Application_Name = Process.GetCurrentProcess().MainModule.ModuleName If Application_Path Is Nothing Then Application_Path = Application.ExecutablePath Try Select Case Startup_User Case Startup_User.All_Users My.Computer.Registry.SetValue("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run", Application_Name, Application_Path, Microsoft.Win32.RegistryValueKind.String) Case Startup_User.Current_User My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", Application_Name, Application_Path, Microsoft.Win32.RegistryValueKind.String) End Select Catch ex As Exception ' Throw New Exception(ex.Message) Return False End Try Return True End Function #End Region
Convierte un array de bytes a string #Region " Byte-Array To String " ' [ Byte-Array To String Function ] ' ' // By Elektro H@cker ' ' Examples : ' Dim Bytes() As Byte = {84, 101, 115, 116} ' T, e, s, t ' MsgBox(Byte_Array_To_String(Bytes)) ' Result: Test Private Function Byte_Array_To_String(ByVal Byte_Array As Byte()) As String Return System.Text.Encoding.ASCII.GetString(Byte_Array) End Function #End Region
Convierte un string a aray de bytes #Region " String to Byte-Array " ' [ String to Byte-Array Function ] ' ' // By Elektro H@cker ' ' Examples : ' Dim Bytes() As Byte = String_to_Byte_Array("Test") ' Byte = {84, 101, 115, 116} Private Function String_to_Byte_Array(ByVal Text As String) As Byte() Return System.Text.Encoding.ASCII.GetBytes(Text) End Function #End Region
Añade una cuenta de usuario al sistema: #Region " Add User Account " ' [ Add User Account Function ] ' ' // By Elektro H@cker ' ' Examples : ' MsgBox(Add_User_Account("New User")) ' Add_User_Account("New User", "MyPass") Private Function Add_User_Account(ByVal UserName As String, Optional ByVal Password As String = Nothing) As Boolean Dim Net_User As New Process() Dim Net_User_Info As New ProcessStartInfo() Net_User_Info.FileName = "CMD.exe" Net_User_Info.Arguments = "/C NET User " & "" & UserName & "" & " " & "" & Password & "" & " /ADD" Net_User_Info.WindowStyle = ProcessWindowStyle.Hidden Net_User.StartInfo = Net_User_Info Net_User.Start() Net_User.WaitForExit() Select Case Net_User.ExitCode Case 0 : Return True ' Account created Case 2 : Return False ' Account already exist Case Else : Return False ' Unknown error End Select End Function #End Region
|
|
|
9302
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 7 Mayo 2013, 14:50 pm
|
Detectar que botón del mouse se ha pinchado: Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles MyBase.MouseClick Select Case e.Button().ToString.ToLower Case "left" ' Left mouse clicked MsgBox("Left mouse clicked") Case "right" ' Right mouse clicked MsgBox("Right mouse clicked") Case "middle" ' Middle mouse clicked MsgBox("Middle mouse clicked") End Select End Sub
Modificar la opacidad del Form cuando se arrastra desde la barra de título: ' Set opacity when moving the form from the TitleBar Protected Overrides Sub DefWndProc(ByRef message As System.Windows.Forms.Message) ' -- Trap left mouse click down on titlebar If CLng(message.Msg) = &HA1 Then If Me.Opacity <> 0.5 Then Me.Opacity = 0.5 ' -- Trap left mouse click up on titlebar ElseIf CLng(message.Msg) = &HA0 Then If Me.Opacity <> 1.0 Then Me.Opacity = 1.0 End If MyBase.DefWndProc(message) End Sub
Convertir "&H" a entero: #Region " Win32Hex To Int " ' [ Win32Hex To Int Function ] ' ' // By Elektro H@cker ' ' Examples: ' MsgBox(Win32Hex_To_Int(&H2S)) ' Result: 2 ' MsgBox(Win32Hex_To_Int(&HFF4)) ' 4084 Private Function Win32Hex_To_Int(ByVal Win32Int As Int32) As Int32 Return CInt(Win32Int) End Function #End Region
Convertir un SID al nombre dle usuario o al dominio+nombre #Region " Get SID UserName " ' [ Get SID UserName ] ' ' Examples: ' MsgBox(Get_SID_UserName("S-1-5-21-148789306-3749789949-2179752015-500")) ' Result: UserName ' MsgBox(Get_SID_UserName("S-1-5-21-148789306-3749789949-2179752015-500")) ' Result: DomainName\UserName Private Declare Unicode Function ConvertStringSidToSidW Lib "advapi32.dll" (ByVal StringSID As String, ByRef SID As IntPtr) As Boolean Private Declare Unicode Function LookupAccountSidW Lib "advapi32.dll" (ByVal lpSystemName As String, ByVal SID As IntPtr, ByVal Name As System.Text.StringBuilder, ByRef cbName As Long, ByVal DomainName As System.Text.StringBuilder, ByRef cbDomainName As Long, ByRef psUse As Integer) As Boolean Shared Function Get_SID_UserName(ByVal SID As String, Optional ByVal Get_Domain_Name As Boolean = False) As String Const size As Integer = 255 Dim domainName As String Dim userName As String Dim cbUserName As Long = size Dim cbDomainName As Long = size Dim ptrSID As New IntPtr(0) Dim psUse As Integer = 0 Dim bufName As New System.Text.StringBuilder(size) Dim bufDomain As New System.Text.StringBuilder(size) If ConvertStringSidToSidW(SID, ptrSID) Then If LookupAccountSidW(String.Empty, _ ptrSID, bufName, _ cbUserName, bufDomain, _ cbDomainName, psUse) Then userName = bufName.ToString domainName = bufDomain.ToString If Get_Domain_Name Then Return String.Format("{0}\{1}", domainName, userName) Else Return userName End If Else Return "" End If Else Return "" End If End Function #End Region
Copia una clave con sus subclaves y valores, a otro lugar del registro. #Region " Reg Copy Key " ' [ Reg Copy Key Function ] ' ' // By Elektro H@cker ' ' Reg_Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", "7-zip") ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip" ' Reg_Copy_Key("HKCU", "Software", "7-Zip", Nothing, "Software", "7-zip") ' Copies "HKCU\Software\7-Zip" to "HKCU\Software\7-Zip" ' Reg_Copy_Key("HKCU", "Software", "7-Zip", "HKLM", "Software", Nothing) ' Copies "HKCU\Software\7-Zip" to "HKLM\Software\" ' Reg_Copy_Key("HKCU", "Software", "7-Zip", "HKLM", Nothing, Nothing) ' Copies "HKCU\Software\7-Zip" to "HKLM\" ' Reg_Copy_Key("HKCU", "\Software\", "\7-Zip\", "HKLM", "\Software\", "\7-zip\") ' (Detects bad syntax) Copies "HKCU\Software\7-Zip" to "HKLM\Software\7-Zip" Private Function Reg_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 = Nothing Dim DestRootKey As Microsoft.Win32.RegistryKey = Nothing Select Case OldRootKey.ToUpper Case "HKCR", "HKEY_CLASSES_ROOT" : OrigRootKey = Microsoft.Win32.Registry.ClassesRoot Case "HKCC", "HKEY_CURRENT_CONFIG" : OrigRootKey = Microsoft.Win32.Registry.CurrentConfig Case "HKCU", "HKEY_CURRENT_USER" : OrigRootKey = Microsoft.Win32.Registry.CurrentUser Case "HKLM", "HKEY_LOCAL_MACHINE" : OrigRootKey = Microsoft.Win32.Registry.LocalMachine Case "HKEY_PERFORMANCE_DATA" : OrigRootKey = Microsoft.Win32.Registry.PerformanceData Case Else : Return False End Select Select Case NewRootKey.ToUpper Case "HKCR", "HKEY_CLASSES_ROOT" : DestRootKey = Microsoft.Win32.Registry.ClassesRoot Case "HKCC", "HKEY_CURRENT_CONFIG" : DestRootKey = Microsoft.Win32.Registry.CurrentConfig Case "HKCU", "HKEY_CURRENT_USER" : DestRootKey = Microsoft.Win32.Registry.CurrentUser Case "HKLM", "HKEY_LOCAL_MACHINE" : DestRootKey = Microsoft.Win32.Registry.LocalMachine Case "HKEY_PERFORMANCE_DATA" : DestRootKey = Microsoft.Win32.Registry.PerformanceData Case Else : Return False End Select 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 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 #End Region
|
|
|
9303
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 7 Mayo 2013, 14:46 pm
|
Crear hotkeys globales fuera del form, usando ComboBoxes. Solo hay que añadir dos comboboxes al form (los valores se añaden al crear la ventana):   #Region " Set Global Hotkeys using ComboBoxes " ' [ Set Global Hotkeys using ComboBoxes Example ] ' ' // By Elektro H@cker ' ' Instructions : ' Instructions: ' 1. Add the "GlobalHotkeys Class" Class to the project. ' 2. Add a ComboBox in the Form with the name "ComboBox_SpecialKeys", with DropDownStyle property. ' 3. Add a ComboBox in the Form with the name "ComboBox_NormalKeys", with DropDownStyle property. Dim SpecialKeys As String() = {"NONE", "ALT", "CTRL", "SHIFT"} Dim NormalKeys As String() = { _ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", _ "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", _ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", _ "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"} Dim SpecialKey As String = SpecialKeys(0) Dim NormalKey As System.Windows.Forms.Keys Dim WithEvents HotKey_Global As Shortcut ' Form load Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load For Each Item In SpecialKeys ComboBox_SpecialKeys.Items.Add(Item) Application.DoEvents() Next For Each Item In NormalKeys ComboBox_NormalKeys.Items.Add(Item) Application.DoEvents() Next ComboBox_SpecialKeys.SelectedItem = SpecialKeys(0) ' ComboBox_NormalKeys.SelectedItem = NormalKeys(0) End Sub ' ComboBoxes SelectedKeys Private Sub ComboBoxes_SelectedIndexChanged(sender As Object, e As EventArgs) Handles _ ComboBox_SpecialKeys.SelectedIndexChanged, _ ComboBox_NormalKeys.SelectedIndexChanged SpecialKey = ComboBox_SpecialKeys.Text Try : Select Case ComboBox_SpecialKeys.Text Case "ALT" NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True) HotKey_Global = Shortcut.Create(Shortcut.Modifier.Alt, NormalKey) Case "CTRL" NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True) HotKey_Global = Shortcut.Create(Shortcut.Modifier.Ctrl, NormalKey) Case "SHIFT" NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True) HotKey_Global = Shortcut.Create(Shortcut.Modifier.Shift, NormalKey) Case "NONE" Dim Number_RegEx As New System.Text.RegularExpressions.Regex("\D") If Number_RegEx.IsMatch(ComboBox_NormalKeys.Text) Then NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), ComboBox_NormalKeys.Text, True) Else NormalKey = [Enum].Parse(GetType(System.Windows.Forms.Keys), (ComboBox_NormalKeys.Text + 96), False) End If HotKey_Global = Shortcut.Create(Shortcut.Modifier.None, NormalKey) End Select Catch : End Try End Sub ' Hotkey is pressed Private Sub HotKey_Press(ByVal s As Object, ByVal e As Shortcut.HotKeyEventArgs) Handles HotKey_Global.Press MsgBox("hotkey clicked: " & SpecialKey & "+" & NormalKey.ToString) End Sub #End Region #Region " GlobalHotkeys Class " Class Shortcut Inherits NativeWindow Implements IDisposable Protected Declare Function UnregisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Integer) As Boolean Protected Declare Function RegisterHotKey Lib "user32.dll" (ByVal handle As IntPtr, ByVal id As Integer, ByVal modifier As Integer, ByVal vk As Integer) As Boolean Event Press(ByVal sender As Object, ByVal e As HotKeyEventArgs) Protected EventArgs As HotKeyEventArgs, ID As Integer Enum Modifier As Integer None = 0 Alt = 1 Ctrl = 2 Shift = 4 End Enum Class HotKeyEventArgs Inherits EventArgs Property Modifier As Shortcut.Modifier Property Key As Keys End Class Class RegisteredException Inherits Exception Protected Const s As String = "Shortcut combination is in use." Sub New() MyBase.New(s) End Sub End Class Private disposed As Boolean Protected Overridable Sub Dispose(ByVal disposing As Boolean) If Not disposed Then UnregisterHotKey(Handle, ID) disposed = True End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub <DebuggerStepperBoundary()> Sub New(ByVal modifier As Modifier, ByVal key As Keys) CreateHandle(New CreateParams) ID = GetHashCode() EventArgs = New HotKeyEventArgs With {.Key = key, .Modifier = modifier} If Not RegisterHotKey(Handle, ID, modifier, key) Then Throw New RegisteredException End Sub Shared Function Create(ByVal modifier As Modifier, ByVal key As Keys) As Shortcut Return New Shortcut(modifier, key) End Function Protected Sub New() End Sub Protected Overrides Sub WndProc(ByRef m As Message) Select Case m.Msg Case 786 RaiseEvent Press(Me, EventArgs) Case Else MyBase.WndProc(m) End Select End Sub End Class #End Region
|
|
|
9304
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 7 Mayo 2013, 11:53 am
|
Me he currado esta class para manejar la aplicación ResHacker, para añadir/eliminar/reemplazar/Extraer iconos u otros tipos de recursos de un archivo: Ejemplos de uso: ResHacker.All_Resources_Extract("C:\File.exe", ResHacker.ResourceType.ICON) ResHacker.All_Resources_Extract("C:\File.dll", ResHacker.ResourceType.BITMAP, "C:\Temp\") ResHacker.MainIcon_Delete("C:\Old.exe", "C:\New.exe") ResHacker.MainIcon_Extract("C:\Program.exe", "C:\Icon.ico") ResHacker.MainIcon_Replace("C:\Old.exe", "C:\New.exe", "C:\Icon.ico") ResHacker.Resource_Add("C:\Old.exe", "C:\New.exe", "C:\Icon.ico", ResHacker.ResourceType.ICON, "Test", 1033) ResHacker.Resource_Delete("C:\Old.exe", "C:\New.exe", ResHacker.ResourceType.ICON, "MAINICON", 0) ResHacker.Resource_Extract("C:\Old.exe", "C:\New.exe", ResHacker.ResourceType.ICON, "MAINICON", 0) ResHacker.Resource_Replace("C:\Old.exe", "C:\New.exe", "C:\Icon.ico", ResHacker.ResourceType.ICON, "MAINICON", 0) ResHacker.Run_Script("C:\Reshacker.txt") ResHacker.Check_Last_Error()
#Region " ResHacker class " Public Class ResHacker ''' <summary> ''' Set the location of ResHacker executable [Default: ".\Reshacker.exe"]. ''' </summary> Public Shared ResHacker_Location As String = ".\ResHacker.exe" ''' <summary> ''' Set the location of ResHacker log file [Default: ".\Reshacker.log"]. ''' </summary> Public Shared ResHacker_Log_Location As String = ResHacker_Location.Substring(0, ResHacker_Location.Length - 4) & ".log" ' Most Known ResourceTypes ''' <summary> ''' The most known ResourceTypes. ''' </summary> Enum ResourceType ASFW AVI BINARY BINDATA BITMAP CURSOR DIALOG DXNAVBARSKINS FONT FTR GIF HTML IBC ICON IMAGE JAVACLASS JPGTYPE LIBRARY MASK MENU MUI ORDERSTREAM PNG RCDATA REGINST REGISTRY STRINGTABLE RT_RCDATA SHADER STYLE_XML TYPELIB UIFILE VCLSTYLE WAVE WEVT_TEMPLATE XML XMLWRITE End Enum ' ------------------ ' MainIcon functions ' ------------------ ''' <summary> ''' Extract the main icon from file. ''' </summary> Public Shared Function MainIcon_Extract(ByVal InputFile As String, _ ByVal OutputIcon As String) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-extract " & """" & InputFile & """" & ", " & """" & OutputIcon & """" & ", ICONGROUP, MAINICON, 0" ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Delete the main icon of file. ''' </summary> Public Shared Function MainIcon_Delete(ByVal InputFile As String, _ ByVal OutputFile As String) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-delete " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", ICONGROUP, MAINICON, 0" ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Replace the main icon of file. ''' </summary> Public Shared Function MainIcon_Replace(ByVal InputFile As String, _ ByVal OutputFile As String, _ ByVal IconFile As String) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-addoverwrite " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & """" & IconFile & """" & ", ICONGROUP, MAINICON, 0" ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ' ---------------------- ' ResourceType functions ' ---------------------- ''' <summary> ''' Add a resource to file. ''' </summary> Public Shared Function Resource_Add(ByVal InputFile As String, _ ByVal OutputFile As String, _ ByVal ResourceFile As String, _ ByVal ResourceType As ResourceType, _ ByVal ResourceName As String, _ Optional ByVal LanguageID As Int32 = 0) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-add " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & """" & ResourceFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Delete a resource from file. ''' </summary> Public Shared Function Resource_Delete(ByVal InputFile As String, _ ByVal OutputFile As String, _ ByVal ResourceType As ResourceType, _ ByVal ResourceName As String, _ Optional ByVal LanguageID As Int32 = 0) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-delete " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Extract a resource from file. ''' </summary> Public Shared Function Resource_Extract(ByVal InputFile As String, _ ByVal OutputFile As String, _ ByVal ResourceType As ResourceType, _ ByVal ResourceName As String, _ Optional ByVal LanguageID As Int32 = 0) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-extract " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ''' <summary> ''' Replace a resource from file. ''' </summary> Public Shared Function Resource_Replace(ByVal InputFile As String, _ ByVal OutputFile As String, _ ByVal ResourceFile As String, _ ByVal ResourceType As ResourceType, _ ByVal ResourceName As String, _ Optional ByVal LanguageID As Int32 = 0) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-addoverwrite " & """" & InputFile & """" & ", " & """" & OutputFile & """" & ", " & """" & ResourceFile & """" & ", " & ResourceType.ToString & ", " & """" & ResourceName & """" & ", " & LanguageID ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ' ---------------------- ' All resources function ' ---------------------- ''' <summary> ''' Extract all kind of resource from file. ''' </summary> Public Shared Function All_Resources_Extract(ByVal InputFile As String, _ ByVal ResourceType As ResourceType, _ Optional ByVal OutputDir As String = Nothing) As Boolean If OutputDir Is Nothing Then OutputDir = InputFile.Substring(0, InputFile.LastIndexOf("\")) _ & "\" _ & InputFile.Split("\").Last.Substring(0, InputFile.Split("\").Last.LastIndexOf(".")) _ & ".rc" Else If OutputDir.EndsWith("\") Then OutputDir = OutputDir.Substring(0, OutputDir.Length - 1) OutputDir += "\" & InputFile.Split("\").Last.Substring(0, InputFile.Split("\").Last.LastIndexOf(".")) & ".rc" End If Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-extract " & """" & InputFile & """" & ", " & """" & OutputDir & """" & ", " & ResourceType.ToString & ",," ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ' --------------- ' Script function ' --------------- ''' <summary> ''' Run a ResHacker script file. ''' </summary> Public Shared Function Run_Script(ByVal ScriptFile As String) As Boolean Try Dim ResHacker As New Process() Dim ResHacker_Info As New ProcessStartInfo() ResHacker_Info.FileName = ResHacker_Location ResHacker_Info.Arguments = "-script " & """" & ScriptFile & """" ResHacker_Info.UseShellExecute = False ResHacker.StartInfo = ResHacker_Info ResHacker.Start() ResHacker.WaitForExit() Return Check_Last_Error() Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function ' ------------------------- ' Check Last Error function ' ------------------------- ''' <summary> ''' Return the last operation error if any [False = ERROR, True = Ok]. ''' </summary> Shared Function Check_Last_Error() Dim Line As String = Nothing Dim Text As IO. StreamReader = IO. File. OpenText(ResHacker_Log_Location ) Do Until Text.EndOfStream Line = Text.ReadLine() If Line.ToString.StartsWith("Error: ") Then MsgBox(Line) Return False End If Loop Text.Close() Text.Dispose() Return True End Function End Class #End Region
|
|
|
9305
|
Media / Multimedia / Re: (consulta) Megui audio desincronizado x264+aac
|
en: 7 Mayo 2013, 11:50 am
|
¿La supuesta desincronización donde se da?, quiero decir, la notas en el reproductor de video, en el editor de video, o donde?
Te lo comento porque algunos reproductores tienen una mala sincronización (ejemplo: umplayer, smplayer) y te desincronizan sobretodo los videos de 1080p con ms e incluso segundos de diferencia, pero en realidad no están desincronizados. Si el problema lo notas al reproducir el video te recomiendo que uses el MediaPlayerClassic (Que no es lo mismo que "Mplayer") para salir de dudas y ver si realmente está desincronizado o no.
Aparte, ¿porque no consideras aumentar/disminuir 2-4 frames al framerate del vídeo final para corregir la desincronizacion de 2 segundos?, lo puedes hacer sin reconvertir y es una solución.
Un saludo.
|
|
|
9306
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 5 Mayo 2013, 08:59 am
|
Para bloquear procesos. ' [ Block Process Functions ] ' ' // By Elektro H@cker ' ' Examples : ' BlockProcess.Block("cmd") ' Blocks a process ' BlockProcess.Block("firefox.exe") ' Blocks a process ' BlockProcess.Unblock("cmd") ' Unblocks a process ' BlockProcess.Unblock("firefox.exe") ' Unblocks a process ' ' BlockProcess.Unblock_All() ' Reset all values and stop timer ' BlockProcess.Monitor_Interval = 5 * 1000 ' BlockProcess.Show_Message_On_Error = True ' BlockProcess.Show_Message_On_blocking = True ' BlockProcess.Message_Text = "I blocked your process: " ' BlockProcess.Message_Title = "Block Process .:: By Elektro H@cker ::." #Region " Block Process Class " Public Class BlockProcess Shared Blocked_APPS As New List(Of String) ' List of process names Shared WithEvents ProcessMon_Timer As New Timer ' App Monitor timer ''' <summary> ''' Shows a MessageBox if error occurs when blocking the app [Default: False]. ''' </summary> Public Shared Show_Message_On_Error As Boolean = False ''' <summary> ''' Shows a MessageBox when app is being blocked [Default: False]. ''' </summary> Public Shared Show_Message_On_blocking As Boolean = False ''' <summary> ''' Set the MessageBox On blocking Text. ''' </summary> Public Shared Message_Text As String = "Process blocked: " ''' <summary> ''' Set the MessageBox On blocking Title. ''' </summary> Public Shared Message_Title As String = "Process Blocked" ''' <summary> ''' Set the App Monitor interval in milliseconds [Default: 200]. ''' </summary> Public Shared Monitor_Interval As Int64 = 200 ''' <summary> ''' Add a process name to the process list. ''' </summary> Public Shared Sub Block(ByVal ProcessName As String) If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4) Blocked_APPS.Add(ProcessName) If Not ProcessMon_Timer.Enabled Then ProcessMon_Timer.Enabled = True End Sub ''' <summary> ''' Delete a process name from the process list. ''' </summary> Public Shared Sub Unblock(ByVal ProcessName As String) If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4) Blocked_APPS.Remove(ProcessName) End Sub ''' <summary> ''' Clear the process list and disables the App Monitor. ''' </summary> Public Shared Sub Unblock_All() ProcessMon_Timer.Enabled = False Blocked_APPS.Clear() End Sub ' Timer Tick Event Shared Sub ProcessMon_Timer_Tick(sender As Object, e As EventArgs) Handles ProcessMon_Timer.Tick For Each ProcessName In Blocked_APPS Dim proc() As Process = Process.GetProcessesByName(ProcessName) Try For proc_num As Integer = 0 To proc.Length - 1 proc(proc_num).Kill() If Show_Message_On_blocking Then MessageBox.Show(Message_Text & ProcessName & ".exe", Message_Title, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) End If Next Catch ex As Exception If Show_Message_On_Error Then MsgBox(ex.Message) ' One of the processes can't be killed End If End Try Next ' Set the Timer interval if is different If Not sender.Interval = Monitor_Interval Then sender.Interval = Monitor_Interval End Sub End Class #End Region
|
|
|
9309
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 4 Mayo 2013, 18:26 pm
|
Un snippet para medir el tiempo transcurrido para un procedimiento o una función o cualquier cosa: MEJORADO:  #Region " Code Execution Time " ' [ Code Execution Time ] ' ' // By Elektro H@cker ' ' Examples : ' Execution_Start() : Threading.Thread.Sleep(500) : Execution_End() Dim Execution_Watcher As New Stopwatch Private Sub Execution_Start() If Execution_Watcher.IsRunning Then Execution_Watcher.Restart() Execution_Watcher.Start() End Sub Private Sub Execution_End() If Execution_Watcher.IsRunning Then MessageBox.Show("Execution watcher finished:" & vbNewLine & vbNewLine & _ "[H:M:S:MS]" & vbNewLine & _ Execution_Watcher.Elapsed.Hours & _ ":" & Execution_Watcher.Elapsed.Minutes & _ ":" & Execution_Watcher.Elapsed.Seconds & _ ":" & Execution_Watcher.Elapsed.Milliseconds & _ vbNewLine & _ vbNewLine & _ "Total H: " & Execution_Watcher.Elapsed.TotalHours & vbNewLine & vbNewLine & _ "Total M: " & Execution_Watcher.Elapsed.TotalMinutes & vbNewLine & vbNewLine & _ "Total S: " & Execution_Watcher.Elapsed.TotalSeconds & vbNewLine & vbNewLine & _ "Total MS: " & Execution_Watcher.ElapsedMilliseconds & vbNewLine, _ "Code execution time", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information, _ MessageBoxDefaultButton.Button1) Execution_Watcher.Reset() Else MessageBox.Show("Execution watcher never started.", _ "Code execution time", _ MessageBoxButtons.OK, _ MessageBoxIcon.Error, _ MessageBoxDefaultButton.Button1) End If End Sub #End Region
|
|
|
9310
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 4 Mayo 2013, 16:44 pm
|
Elimina el contenido del portapapeles: Private Sub Delete_Clipboard() Clipboard.SetText(vbCr) End Sub
Devuelve el color de un pixel en varios formatos: CORREGIDO, si el valor era 0, el formato Hexadecimal devolvía un 0 de menos. #Region " Get Pixel Color " ' [ Get Pixel Color Function ] ' ' // By Elektro H@cker ' ' Examples : ' ' Dim RGB As Color = Get_Pixel_Color(MousePosition.X, MousePosition.Y, ColorType.RGB) ' MsgBox(Get_Pixel_Color(100, 100, ColorType.RGB).ToString) ' MsgBox(Get_Pixel_Color(100, 100, ColorType.HEX)) ' MsgBox(Get_Pixel_Color(100, 100, ColorType.HTML)) <System.Runtime.InteropServices.DllImport("user32.dll")> Shared Function GetDC(hwnd As IntPtr) As IntPtr End Function <System.Runtime.InteropServices.DllImport("user32.dll")> Shared Function ReleaseDC(hwnd As IntPtr, hdc As IntPtr) As Int32 End Function <System.Runtime.InteropServices.DllImport("gdi32.dll")> Shared Function GetPixel(hdc As IntPtr, nXPos As Integer, nYPos As Integer) As UInteger End Function Public Enum ColorType RGB HEX HTML End Enum Public Function Get_Pixel_Color(ByVal x As Int32, ByVal y As Int32, ByVal ColorType As ColorType) Dim hdc As IntPtr = GetDC(IntPtr.Zero) Dim pixel As UInteger = GetPixel(hdc, x, y) ReleaseDC(IntPtr.Zero, hdc) Dim RGB As Color = Color.FromArgb(CType((pixel And &HFF), Integer), CType((pixel And &HFF00), Integer) >> 8, CType((pixel And &HFF0000), Integer) >> 16) Dim R As Int16 = RGB.R, G As Int16 = RGB.G, B As Int16 = RGB.B Dim HEX_R As String, HEX_G As String, HEX_B As String Select Case ColorType Case ColorType.RGB : Return RGB Case ColorType.HEX If Hex(R) = Hex(0) Then HEX_R = "00" Else HEX_R = Hex(R) If Hex(G) = Hex(0) Then HEX_G = "00" Else HEX_G = Hex(G) If Hex(B) = Hex(0) Then HEX_B = "00" Else HEX_B = Hex(B) Return (HEX_R & HEX_G & HEX_B) Case ColorType.HTML : Return ColorTranslator.ToHtml(RGB) Case Else : Return Nothing End Select End Function #End Region
Crear un archivo comprimido autoextraible (SFX) con la librería SevenZipSharp: #Region " SevenZipSharp Compress SFX " ' [ SevenZipSharp Compress SFX Function ] ' ' // By Elektro H@cker ' ' Instructions : ' 1. Add a reference to "SevenZipSharp.dll". ' 2. Add the "7z.dll" or "7z64.dll" files to the project. ' 3. Add the "7z.sfx" and "7zCon.sfx" files to the project. ' 4. Use the code below. ' ' Examples : ' SevenZipSharp_Compress_SFX("C:\File.txt") ' File will be compressed in the same dir. ' SevenZipSharp_Compress_SFX("C:\File.txt", "C:\Compressed\File.exe") ' File will be compressed in "C:\Compressed\". ' SevenZipSharp_Compress_SFX("C:\Folder\", , , , , , , "Password") ' Folder will be compressed with the given password. ' SevenZipSharp_Compress_SFX("C:\File.txt", , SevenZipSharp_SFX_Module.Console, CompressionLevel.Fast) ' Imports SevenZip ' Dim dll As String = "7z.dll" Public Enum SevenZipSharp_SFX_Module Normal Console End Enum Private Function SevenZipSharp_Compress_SFX(ByVal Input_DirOrFile As String, _ Optional ByVal OutputFileName As String = Nothing, _ Optional ByVal SFX_Module As SevenZipSharp_SFX_Module = SevenZipSharp_SFX_Module.Normal, _ Optional ByVal CompressionLevel As CompressionLevel = CompressionLevel.Normal, _ Optional ByVal Password As String = Nothing) As Boolean ' Create the .7z file Try ' Set library path SevenZipCompressor.SetLibraryPath(dll) ' Create compressor Dim Compressor As SevenZipCompressor = New SevenZipCompressor() ' Set compression parameters Compressor.CompressionLevel = CompressionLevel ' Archiving compression level. Compressor.CompressionMethod = CompressionMethod.Lzma ' Compression Method Compressor.ArchiveFormat = OutArchiveFormat.SevenZip ' Compression file format Compressor.CompressionMode = CompressionMode.Create ' Append files to compressed file or overwrite the compressed file. Compressor.DirectoryStructure = True ' Preserve the directory structure. Compressor.IncludeEmptyDirectories = True ' Include empty directories to archives. Compressor.ScanOnlyWritable = False ' Compress files only open for writing. Compressor.EncryptHeaders = False ' Encrypt 7-Zip archive headers Compressor.TempFolderPath = System.IO.Path.GetTempPath() ' Temporary folder path Compressor.FastCompression = False ' Compress as fast as possible, without calling events. Compressor.PreserveDirectoryRoot = True ' Preserve the directory root for CompressDirectory. Compressor.ZipEncryptionMethod = ZipEncryptionMethod.ZipCrypto ' Encryption method for zip archives. Compressor.DefaultItemName = "File.7z" ' Item name used when an item to be compressed has no name, for example, when you compress a MemoryStream instance ' Add Progress Handler ' AddHandler Compressor.Compressing, AddressOf SevenZipSharp_Compress_Progress ' Removes the end slash ("\") if given for a directory If Input_DirOrFile.EndsWith("\") Then Input_DirOrFile = Input_DirOrFile.Substring(0, Input_DirOrFile.Length - 1) ' Generate the OutputFileName if any is given. If OutputFileName Is Nothing Then OutputFileName = (My.Computer.FileSystem.GetFileInfo(Input_DirOrFile).DirectoryName & "\" & (Input_DirOrFile.Split("\").Last) & ".tmp").Replace("\\", "\") Else OutputFileName = OutputFileName & ".tmp" End If ' Check if given argument is Dir or File ...then start the compression If IO.Directory.Exists(Input_DirOrFile) Then ' Is a Dir If Not Password Is Nothing Then Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True, Password) Else Compressor.CompressDirectory(Input_DirOrFile, OutputFileName, True) End If ElseIf IO. File. Exists(Input_DirOrFile ) Then ' Is a File If Not Password Is Nothing Then Compressor.CompressFilesEncrypted(OutputFileName, Password, Input_DirOrFile) Else Compressor.CompressFiles(OutputFileName, Input_DirOrFile) End If End If ' Create the SFX file ' Create the SFX compressor Dim compressorSFX As SevenZipSfx = New SevenZipSfx(SfxModule.Default) ' Set SFX Module path If SFX_Module = SevenZipSharp_SFX_Module.Normal Then compressorSFX.ModuleFileName = ".\7z.sfx" ElseIf SFX_Module = SevenZipSharp_SFX_Module.Console Then compressorSFX.ModuleFileName = ".\7zCon.sfx" End If ' Start the compression ' Generate the OutputFileName if any is given. Dim SFXOutputFileName As String If OutputFileName.ToLower.EndsWith(".exe.tmp") Then SFXOutputFileName = OutputFileName.Substring(0, OutputFileName.Length - 4) Else SFXOutputFileName = OutputFileName.Substring(0, OutputFileName.Length - 4) & ".exe" End If compressorSFX.MakeSfx(OutputFileName, SFXOutputFileName) ' Delete the 7z tmp file Try : IO. File. Delete(OutputFileName ) : Catch : End Try Catch ex As Exception 'Return False ' File not compressed Throw New Exception(ex.Message) End Try Return True ' File compressed End Function ' Public Sub SevenZipSharp_Compress_SFX_Progress(ByVal sender As Object, ByVal e As ProgressEventArgs) ' MsgBox("Percent compressed: " & e.PercentDone) ' End Sub #End Region
|
|
|
|
|
|
|