8891
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
en: 8 Junio 2013, 06:49 am
Suspender o continuar un proceso externo:
VIDEO (Corregido un pequeño bug de última hora en la función "resume-thread" al comprobar si existia el proceso en el diccionario.)
#Region " Pause-Resume Thread Class "
Public Class Process_Thread
' [ Pause-Resume Thread Functions ]
'
' // By Elektro H@cker
'
' Examples :
'
' Process_Thread.Pause_Thread("ffmpeg.exe") ' Pause ffmpeg.exe (with thread 0)
' Process_Thread.Resume_Thread("ffmpeg.exe") ' Resume ffmpeg.exe (with thread 0)
' Process_Thread.Pause_Thread("cmd.exe", , True) ' Pause all instances of cmd.exe (with thread 0)
' Process_Thread.Resume_Thread("cmd.exe", , True) ' Resume all instances of cmd.exe (with thread 0)
' Process_Thread.Pause_Thread("Process.exe", 2) ' Pause the thread 2 of "Process.exe"
' Process_Thread.Resume_Thread("Process.exe", 2) ' Resume the thread 2 of "Process.exe"
<System.Runtime .InteropServices .DllImport ( "kernel32.dll" ) > _
Private Shared Function OpenThread( ByVal dwDesiredAccess As Integer , ByVal bInheritHandle As Boolean , ByVal dwThreadId As UInt32) As IntPtr
End Function
<System.Runtime .InteropServices .DllImport ( "kernel32.dll" ) > _
Private Shared Function SuspendThread( hThread As IntPtr) As UInteger
End Function
<System.Runtime .InteropServices .DllImport ( "kernel32.dll" ) > _
Private Shared Function ResumeThread( hThread As IntPtr) As UInt32
End Function
<System.Runtime .InteropServices .DllImport ( "kernel32.dll" , SetLastError:= True ) > _
Private Shared Function CloseHandle( ByVal hObject As IntPtr) As <System.Runtime .InteropServices .MarshalAs ( System.Runtime .InteropServices .UnmanagedType .Bool ) > Boolean
End Function
''' <summary>
''' Dictionary to store the current paused threads.
''' </summary>
Public Shared Thread_Handle_Dictionary
As New Dictionary ( Of String , IntPtr
)
#Region " Pause Thread "
''' <summary>
''' Function to pause a thread.
''' </summary>
'''
''' <param name="Process_Name">The name of the process, ex: cmd.exe</param>
''' <param name="Thread_Number">The thread to pause, ex: 0</param>
''' <param name="Recursive"> <value name="True">Pause the thread in all processes found recursively.</value></param>
''' <returns>True if the process is found; otherwise, False.</returns>
Public Shared Function Pause_Thread( ByRef Process_Name As String , _
Optional ByVal Thread_Number As Int32 = 0 , _
Optional ByVal Recursive As Boolean = False ) As Boolean
If Process_Name.ToLower .EndsWith ( ".exe" ) Then _
Process_Name = Process_Name.Substring ( 0 , Process_Name.Length - 4 )
Dim proc( ) As Process = Process.GetProcessesByName ( Process_Name)
If Not proc.Length = 0 Then
If Recursive Then
For proc_num As Integer = 0 To proc.Length - 1
Try
Thread_Handle_Dictionary.Add ( Process_Name.ToLower & Thread_Number.ToString & ";" & proc( proc_num) .Handle .ToString , _
OpenThread( & H2, True , proc( proc_num) .Threads ( Thread_Number) .Id ) )
SuspendThread( Thread_Handle_Dictionary.Item ( Process_Name.ToLower & Thread_Number.ToString & ";" & proc( proc_num) .Handle .ToString ) )
Application.DoEvents ( )
Catch ex As Exception
MsgBox ( ex.Message ) ' The handle already exist in the Dictionary.
Return False
End Try
Next
Else
Try
Thread_Handle_Dictionary.Add ( Process_Name.ToLower & Thread_Number.ToString & ";" & proc( 0 ) .Handle .ToString , _
OpenThread( & H2, True , proc( 0 ) .Threads ( Thread_Number) .Id ) )
SuspendThread( Thread_Handle_Dictionary.Item ( Process_Name.ToLower & Thread_Number.ToString & ";" & proc( 0 ) .Handle .ToString ) )
Catch ex As Exception
MsgBox ( ex.Message ) ' The handle already exist in the Dictionary.
Return False
End Try
End If
Else ' proc.Length = 0
Throw New Exception( "Process " "" & Process_Name & "" " not found." )
Return False
End If
Return True
End Function
#End Region
#Region " Resume Thread "
''' <summary>
''' Function to resume a thread.
''' </summary>
'''
''' <param name="Process_Name">The name of the process, ex: cmd.exe</param>
''' <param name="Thread_Number">The thread to resume, ex: 0</param>
''' <param name="Recursive"> <value name="True">Resume the thread in all processes found recursively.</value></param>
''' <returns>True if the process is found; otherwise, False.</returns>
Public Shared Function Resume_Thread( ByRef Process_Name As String , _
Optional ByVal Thread_Number As Int32 = 0 , _
Optional ByVal Recursive As Boolean = False ) As Boolean
If Process_Name.ToLower .EndsWith ( ".exe" ) Then _
Process_Name = Process_Name.Substring ( 0 , Process_Name.Length - 4 )
Dim Process_Exist As Boolean = False ' To check if process exist in the dictionary.
Dim Temp_Dictionary
As New Dictionary ( Of String , IntPtr
) ' Replic of the "Thread_Handle_Dictionary" dictionary.
For Each Process In Thread_Handle_Dictionary
If Process.Key .StartsWith ( Process_Name.ToLower & Thread_Number.ToString ) Then Process_Exist = True
Temp_Dictionary.Add ( Process.Key , Process.Value )
Next
If Process_Exist Then
If Recursive Then
For Each Process In Temp_Dictionary
If Process.Key .ToLower .Contains ( Process_Name.ToLower & Thread_Number.ToString ) Then
ResumeThread( Process.Value )
CloseHandle( Process.Value )
Thread_Handle_Dictionary.Remove ( Process.Key )
End If
Application.DoEvents ( )
Next
Else
For Each Process In Temp_Dictionary
If Process.Key .ToLower .Contains ( Process_Name.ToLower & Thread_Number.ToString ) Then
ResumeThread( Process.Value )
CloseHandle( Process.Value )
Thread_Handle_Dictionary.Remove ( Process.Key )
Exit For
End If
Application.DoEvents ( )
Next
End If
Return True
Else
Throw New Exception( "Process " "" & Process_Name & "" " with thread number " "" & Thread_Number & "" " not found." )
Return False
End If
End Function
#End Region
End Class
#End Region
8892
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
en: 8 Junio 2013, 04:43 am
Ahora me pongo yo critico, y para que coño quiero saber la versión de mi IE? XD Hombre, se me ocurren ideas tal como parchear algunos errores en los webbrowsers pero, es poca cosa... xD
La idea es conocer la versión de IExplorer
de otro PC que no sea el tuyo/mio para anticiparse a posibles errores, por ejemplo si te pagan por una aplicación y quieres usar el render de IE10 en un webbrowser pero ese PC tiene IE8 pues...cagada, no?
Un saludo!
8893
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
en: 7 Junio 2013, 21:14 pm
Devuelve la versión instalada de InternetExplorer en el PC:
#Region " Get IExplorer Version "
' [ Get IExplorer Version Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Get_IExplorer_Version) ' Result: 8
' MsgBox(Get_IExplorer_Version(True)) ' Result: 8.00.7600.16385
Private Function Get_IExplorer_Version( Optional ByVal Long_Version As Boolean = False ) As String
Try
If Long_Version Then
Return FileVersionInfo.GetVersionInfo ( Environment.GetFolderPath ( Environment.SpecialFolder .System ) & "\ieframe.dll" ) .ProductVersion
Else
Return FileVersionInfo.GetVersionInfo ( Environment.GetFolderPath ( Environment.SpecialFolder .System ) & "\ieframe.dll" ) .ProductVersion .Split ( "." ) .First
End If
Catch ex As Exception
MsgBox ( ex.Message )
Return 0
End Try
End Function
#End Region
8894
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
en: 7 Junio 2013, 21:01 pm
Modifica el modo de renderizado de IExplorer sobre una aplicación, es decir, el modo de renderizado para un "WebBrowser control"
#Region " Set IExplorer Rendering Mode "
' [ Set IExplorer Rendering Mode ]
'
' // By Elektro H@cker
'
' Examples :
' Set_IExplorer_Rendering_Mode(IExplorer_Renders.IE10)
' Set_IExplorer_Rendering_Mode(IExplorer_Renders.IE10_DOCTYPE, "Application.exe")
Public Enum IExplorer_Renders As Int16
IE10 = 10001 ' Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.
IE10_DOCTYPE = 10000 ' Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.
IE9 = 9999 ' Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
IE9_DOCTYPE = 9000 ' Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.
IE8 = 8888 ' Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
IE8_DOCTYPE = 8000 ' Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.
IE7 = 7000 ' Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.
End Enum
Private Sub Set_IExplorer_Rendering_Mode( ByVal IExplorer_Render As IExplorer_Renders, _
Optional ByVal Application_Name As String = Nothing )
If Application_Name Is Nothing Then Application_Name = Process.GetCurrentProcess ( ) .ProcessName & ".exe"
Try
My.Computer .Registry .SetValue ( _
"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION" , _
Application_Name, IExplorer_Render, Microsoft.Win32 .RegistryValueKind .DWord )
Catch ex As Exception
MsgBox ( ex.Message )
End Try
End Sub
#End Region
Bloquear popups en un webbrowser
Private Sub WebBrowser_NewWindow( ByVal sender As Object , ByVal e As System.ComponentModel .CancelEventArgs ) _
Handles WebBrowser1.NewWindow
e.Cancel = True
End Sub
Bloquear iFrames en un webbrowser
Private Sub WebBrowser_DocumentCompleted( sender As Object , e As WebBrowserDocumentCompletedEventArgs) _
Handles WebBrowser1.DocumentCompleted
For Each element As HtmlElement In CType ( sender, WebBrowser) .Document .GetElementsByTagName ( "iframe" )
element.OuterHtml = String .Empty
Application.DoEvents ( )
Next
End Sub
8895
Programación / Scripting / Re: Instalar programa en Batch
en: 7 Junio 2013, 17:14 pm
Tu pregunta no tiene nada que ver con Batch, sinó con el instalador.
Hay varios tipos de instaladores, al igual que varios tipos de móviles y varios tipos de sistemas operativos,
debes informarte con cual
InstallBuilder ha sido creado ese installer, y luego buscar sus opciones desatendidas (
Silent switches ).
EDITO: Además, en caso de ser un
WindowsInstaller (
MSI ), se pueden programar de muchas maneras, se puede nombrar cada opción (paquete) como al programador del instalador le haya dado la gana nombrarlos, solo vas a saber como se llaman buscando en Google para visitar la documentación de soporte del fabricante, y leer, o usando el editor de MSI
Orca para saber los nombres de los atributos y las "opciones" de ese installer,
reálmente lo que estás pidiendo es lo mismo que pedir que te lea el futuro un adivino, porque es imposible saberlo sin que des los datos necesarios.
Si se trata de un MSI y es un instalador de algún programa conocido, segúramente la información que necesites ya está por los rincones de Google.
...El archivo bat sería algo así:
@Echo off Instalador-InnoSetup.exe /silent Instalador-WindowsInstaller.msi /qn /norestart INSTALLDIR="C:\Ruta" ADDLOCAL=Nombre-de-paquete-a-instalar Pause&Exit Saludos.
8896
Programación / .NET (C#, VB.NET, ASP) / Re: ¿Cómo encontrar una cadena dentro de un párrafo de texto?
en: 7 Junio 2013, 10:41 am
Hay varias formas.
Si estás usando un html/xml/xmlns lo mejor quizás sería que uses htmlagilitypack:
http://htmlagilitypack.codeplex.com/ ...Pero es el método más dificil de entre los que existen, y dependiendo del conteido (sopa de tags) podría no serte útil en absoluto.
Puedes usar el método
SPLIT :
http://msdn.microsoft.com/en-us/library/system.string.split.aspx for each item in variable_de_tipo_String.split ( controlchars.quote ) : msgbox ( item) : next
O mi manera favorita, Expresiones regulares:
http://en.wikipedia.org/wiki/Regular_expression Output:
http://1.bp.blogspot.com/-NhL7eyZF_bM/UC6AO7LanyI/AAAAAAAADNw/VkfXa-fNxpA/s1600/glucides-vitamines-fruits.jpg http://1.bp.blogspot.com/-NhL7eyZF_bM/UC6AO7LanyI/AAAAAAAADNw/VkfXa-fNxpA/s1600/glucides-vitamines-fruits11.jpg Public Class Form1
Private Sub Form1_Load( sender As Object , e As EventArgs) Handles MyBase .Load
Dim str As String = <a><![ CDATA[ <a href= "http://1.bp.blogspot.com/-NhL7eyZF_bM/UC6AO7LanyI/AAAAAAAADNw/VkfXa-fNxpA/s1600/glucides-vitamines-fruits.jpg" / > <a href= "http://1.bp.blogspot.com/-NhL7eyZF_bM/UC6AO7LanyI/AAAAAAAADNw/VkfXa-fNxpA/s1600/glucides-vitamines-fruits11.jpg" / >] ] ></ a>.Value
Dim regex As String = <a><![ CDATA[ ( http:// |https:// |www) ( [ \ w+ ?\ .\ w+ ] ) + ( [ a- zA- Z0- 9 \ ~\ !\ @\ #\ $\ %\^\& amp;\*\ ( \ ) _\-\=\+\\\/\ ?\ .\ :\ ;\ '\,]*)?]]></a>.Value
For Each match In RegEx_Matches_To_List( str , regex) : MsgBox ( match) : Next
End Sub
#Region " RegEx Matches To List "
' [ RegEx Matches To List Function ]
'
' // By Elektro H@cker
Private Function RegEx_Matches_To_List( ByVal str As String , ByVal RegEx_Pattern As String , _
Optional ByVal Group As Int32 = 0 , _
Optional ByVal IgnoreCase As Boolean = True ) _
As List( Of String )
Dim regex_option As System.Text .RegularExpressions .RegexOptions
If IgnoreCase Then regex_option = System.Text .RegularExpressions .RegexOptions .IgnoreCase _
Else regex_option = System.Text .RegularExpressions .RegexOptions .None
Dim match As System.Text .RegularExpressions .Match = System.Text .RegularExpressions .Regex .Match ( str , RegEx_Pattern, regex_option)
Dim Matches_List As New List( Of String )
Do While match.Success
Matches_List.Add ( match.Groups ( Group) .ToString )
match = match.NextMatch ( )
Application.DoEvents ( )
Loop
Return Matches_List
End Function
#End Region
End Class
Saludos.
8897
Programación / .NET (C#, VB.NET, ASP) / Re: Crear PictureBox a través de una config .ini?
en: 7 Junio 2013, 09:58 am
Tengo otra duda, he puesto Panel1.Controls.Add(Panel1) Dentro del For, ahora los pics tienen las propiedades del Panel1 xD
Claro, las propiedades del container las heredan los controles que añades dentro del container...
pasa lo mismo si los creas/añades desde el designer .
Modifica las propiedades que consideres "conflictivas" del panel
un saludo
8898
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
en: 7 Junio 2013, 09:56 am
Ostia, ese es el code en el que te he
ayudado?
No verdad, es el siguiente no?
¿En que parte del código ves algo elevado al cuadrado? xD
Me ayudaste a resolver un problema de una operación matemática en una aplicación donde yo usaba un code, el code o la aplicación es irelevante, pero si, te refieres al code de las combinaciones xD
Salu2
8899
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
en: 7 Junio 2013, 05:23 am
Formatear un número:
#Region " Format Number "
' [ Format Number Function ]
'
' // By Elektro H@cker
'
' Examples :
' MsgBox(Format_Number(50000)) ' Result: 50.000
' MsgBox(Format_Number(-12345.33)) ' Result: -12.345,33
Private Function Format_Number( ByVal Number As Object ) As String
Select Case Number.GetType ( )
Case GetType ( Int16) , GetType ( Int32) , GetType ( Int64)
Return FormatNumber ( Number, TriState.False )
Case Else
Return FormatNumber ( Number, , TriState.False )
End Select
End Function
#End Region
Crear un textbox con una máscara de asteriscos (para introducir passwords):
TextBox1.Text = "Elektro" ' Set a random text.
TextBox1.PasswordChar = "*" ' The character to use in the mask.
TextBox1.MaxLength = 8 ' The maximum length of characters inside the textbox.
MsgBox ( TextBox1.Text ) ' Result: Elektro
Genera todas las combinaciones posibles de una serie de caracteres:
(Este código es ORO por su sencillez y eficacia):
#Region " Permute all combinations of characters"
' [ Permute Characters Function ]
'
' Examples :
' Dim Permutations As IEnumerable = Permute_Characters("abc", 2)
' For Each Permutation As IEnumerable(Of Char) In Permutations : RichTextBox1.Text &= vbNewLine & Permutation.ToArray : Next
Private Shared Function Permute_Characters( Of T) ( list As IEnumerable( Of T) , length As Integer ) As IEnumerable( Of IEnumerable( Of T) )
If length = 1 Then
Return list.[ Select ] ( Function ( x) New T( ) { x} )
Else
Return Permute_Characters( list, length - 1 ) .SelectMany ( Function ( x) list, Function ( t1, t2) t1.Concat ( New T( ) { t2} ) )
End If
End Function
#End Region
Resultado:
8900
Programación / .NET (C#, VB.NET, ASP) / Re: Crear PictureBox a través de una config .ini?
en: 7 Junio 2013, 04:19 am
Pero Seazoux, ya que haces un copy/paste al menos modifica lo de "chk_" por algo como "pcb_" para que en un futuro, al volver a leer ese código, entiendas lo que hiciste xD.
Los pictureboxes no tienen la propiedad "Text", así que elimina esa línea.
No los ves porque son transparentes, añádele un:
pcb_(pcb_num).BackColor = Color.Red Y agranda el valor del "top" a 80 o 90, porque 20 lo puse para Checkboxes, y los pictureboxes por defecto son el triple de anchos que un checkbox, vas a ver una columna roja y ya.
Saludos