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


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


  Mostrar Mensajes
Páginas: 1 ... 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 [756] 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 ... 1258
7551  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 9 Marzo 2014, 16:27 pm
Unos snippets para imitar las macros "LoByte", "LoWord", "LoDword", etc, usando la Class BitConverter, la cual, aunque necesita hacer más trabajo, me parece una solución mucho mas elegante que las que se pueden encontrar por ahí, e igual de efectiva.


Código
  1.    ' Get LoByte
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetLoByte(1587S)) ' Result: 51
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the low-order byte of an 'Int16' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int16' value that contains both the LoByte and the HiByte.</param>
  11.    ''' <returns>The return value is the low-order byte.</returns>
  12.    Public Shared Function GetLoByte(ByVal value As Short) As Byte
  13.  
  14.        Return BitConverter.GetBytes(value).First
  15.  
  16.    End Function

Código
  1.    ' Get HiByte
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetHiByte(1587S)) ' Result: 6
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the high-order byte of an 'Int16' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int16' value that contains both the LoByte and the HiByte.</param>
  11.    ''' <returns>The return value is the high-order byte.</returns>
  12.    Public Shared Function GetHiByte(ByVal value As Short) As Byte
  13.  
  14.        Return BitConverter.GetBytes(value).Last
  15.  
  16.    End Function

Código
  1.    ' Get LoWord
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetLoWord(13959358I)) ' Result: 190S
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the low-order word of an 'Int32' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int32' value that contains both the LoWord and the HiWord.</param>
  11.    ''' <returns>The return value is the low-order word.</returns>
  12.    Public Shared Function GetLoWord(ByVal value As Integer) As Short
  13.  
  14.        Return BitConverter.ToInt16(BitConverter.GetBytes(value), 0)
  15.  
  16.    End Function

Código
  1.    ' Get HiWord
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetHiWord(13959358I)) ' Result: 213S
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the high-order word of an 'Int32' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int32' value that contains both the LoWord and the HiWord.</param>
  11.    ''' <returns>The return value is the high-order word.</returns>
  12.    Public Shared Function GetHiWord(ByVal value As Integer) As Short
  13.  
  14.        Return BitConverter.ToInt16(BitConverter.GetBytes(value), 2)
  15.  
  16.    End Function

Código
  1.    ' Get LoDword (As Unsigned Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetLoDword(328576329396160UL)) ' Result: 2741317568UI
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the low-order double word of an 'UInt64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'UInt64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <returns>The return value is the low-order double word.</returns>
  12.    Public Shared Function GetLoDword(ByVal value As ULong) As UInteger
  13.  
  14.        Return BitConverter.ToUInt32(BitConverter.GetBytes(value), 0)
  15.  
  16.    End Function

Código
  1.    ' Get HiDword (As Unsigned Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetHiDword(328576329396160UL)) ' Result: 76502UI
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the high-order double word of an 'UInt64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'UInt64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <returns>The return value is the high-order double word.</returns>
  12.    Public Shared Function GetHiDword(ByVal value As ULong) As UInteger
  13.  
  14.        Return BitConverter.ToUInt32(BitConverter.GetBytes(value), 4)
  15.  
  16.    End Function

Código
  1.    ' Get LoDword (As Signed Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetLoDword(328576329396160L)) ' Result: -1553649728I
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the low-order double word of an 'Int64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <returns>The return value is the low-order double word.</returns>
  12.    Public Shared Function GetLoDword(ByVal value As Long) As Integer
  13.  
  14.        Return BitConverter.ToInt32(BitConverter.GetBytes(value), 0)
  15.  
  16.    End Function

Código
  1.    ' Get HiDword (As Signed Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(GetHiDword(328576329396160L)) ' Result: 76502I
  6.    '
  7.    ''' <summary>
  8.    ''' Gets the high-order double word of an 'Int64' value.
  9.    ''' </summary>
  10.    ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param>
  11.    ''' <returns>The return value is the high-order double word.</returns>
  12.    Public Shared Function GetHiDword(ByVal value As Long) As Integer
  13.  
  14.        Return BitConverter.ToInt32(BitConverter.GetBytes(value), 4)
  15.  
  16.    End Function

Código
  1.    ' Make Word
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(MakeWord(51S, 6S)) ' Result: 1587S
  6.    '
  7.    ''' <summary>
  8.    ''' Makes an 'Int16' value from two bytes.
  9.    ''' </summary>
  10.    ''' <param name="LoByte">Indicates the low-order byte.</param>
  11.    ''' <param name="HiByte">Indicates the high-order byte.</param>
  12.    ''' <returns>The 'Int16' value.</returns>
  13.    Public Shared Function MakeWord(ByVal LoByte As Byte,
  14.                                    ByVal HiByte As Byte) As Short
  15.  
  16.        Return BitConverter.ToInt16(New Byte() {LoByte, HiByte}, 0)
  17.  
  18.    End Function

Código
  1.    ' Make Dword
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(MakedWord(190S, 213S)) ' Result: 13959358I
  6.    '
  7.    ''' <summary>
  8.    ''' Makes an 'Int32' value from two 'Int16' values.
  9.    ''' </summary>
  10.    ''' <param name="LoWord">Indicates the low-order word.</param>
  11.    ''' <param name="HiWord">Indicates the high-order word.</param>
  12.    ''' <returns>The 'Int32' value.</returns>
  13.    Public Shared Function MakeDword(ByVal LoWord As Short,
  14.                                     ByVal HiWord As Short) As Integer
  15.  
  16.        Dim LoBytes As Byte() = BitConverter.GetBytes(LoWord)
  17.        Dim HiBytes As Byte() = BitConverter.GetBytes(HiWord)
  18.        Dim Combined As Byte() = LoBytes.Concat(HiBytes).ToArray
  19.  
  20.        Return BitConverter.ToInt32(Combined, 0)
  21.  
  22.    End Function

Código
  1.    ' Make Long (From An Unsigned Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(MakeLong(2741317568UI, 76502UI)) ' Result: 328576329396160UL
  6.    '
  7.    ''' <summary>
  8.    ''' Makes an 'UInt64' value from two 'UInt32' values.
  9.    ''' </summary>
  10.    ''' <param name="LoDword">Indicates the low-order Dword.</param>
  11.    ''' <param name="HiDword">Indicates the high-order Dword.</param>
  12.    ''' <returns>The 'UInt64' value.</returns>
  13.    Public Shared Function MakeLong(ByVal LoDword As UInteger,
  14.                                    ByVal HiDword As UInteger) As ULong
  15.  
  16.        Dim LoBytes As Byte() = BitConverter.GetBytes(LoDword)
  17.        Dim HiBytes As Byte() = BitConverter.GetBytes(HiDword)
  18.        Dim Combined As Byte() = LoBytes.Concat(HiBytes).ToArray
  19.  
  20.        Return BitConverter.ToUInt64(Combined, 0)
  21.  
  22.    End Function

Código
  1.    ' Make Long (From a Signed Integer)
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' MsgBox(MakeLong(-1553649728I, 76502I)) ' Result: 328576329396160L
  6.    '
  7.    ''' <summary>
  8.    ''' Makes an 'Int64' value from two 'Int32' values.
  9.    ''' </summary>
  10.    ''' <param name="LoDword">Indicates the low-order Dword.</param>
  11.    ''' <param name="HiDword">Indicates the high-order Dword.</param>
  12.    ''' <returns>The 'Int64' value.</returns>
  13.    Public Shared Function MakeLong(ByVal LoDword As Integer,
  14.                                    ByVal HiDword As Integer) As Long
  15.  
  16.        Dim LoBytes As Byte() = BitConverter.GetBytes(LoDword)
  17.        Dim HiBytes As Byte() = BitConverter.GetBytes(HiDword)
  18.        Dim Combined As Byte() = LoBytes.Concat(HiBytes).ToArray
  19.  
  20.        Return BitConverter.ToInt64(Combined, 0)
  21.  
  22.    End Function
7552  Programación / Scripting / Re: Suma de variables dentro de bucle for en .bat en: 9 Marzo 2014, 04:09 am
Hombre, los metadatos no cambian por si solos, y algo leí hace mucho tiempo sobre que Windows Media Player modifica los metadatos de los audios sin previo aviso ...cuando este considera necesario actualizarlos (otra de las grandes ideas desagradables por parte de Microsoft).

¿ Probaste con otro reproductor, por ejemplo ...Winamp ?

Las dos lineas de código que muestras hacen exáctamente lo mismo, y me apostaría todo lo que tengo a que el problema es este (solo es una suposición):

En la primera linea, osea en el For, le das como título a las canciones un número seguido de un punto y más números "5.XX",
los (pesados) algoritmos de Windows Media Player segúramente escanearán el título de la canción y determinarán que ese tipo de título (número seguido de un punto) se trata de un título sin formatear, a continuación, se enciende una bombillita que dice: "he, vamos a cambiarle el título a esto sin avisarle al usuario, seguro que nos lo agradecerá :D!"

En cambio, esto no te sucede en la segunda linea que muestras porque el título de la canción que le estás asignando al archivo ("hola") es normal, WMP lo considera un título formateado corréctamente, y entonces no hay motivo para que WMP quiera actualizar los tags.

Como no estoy muy seguro de si ese será el problema, puedes hacer la prueba asignando manualmente ese tipo de título a una canción, y abrirla en el WMP para salir de dudas:
Código:
id3 -1 -2 -t "5.1" "36_PISTA.mp3"

En resumen, y suponiendo que ese sea el problema: O le asignas títulos normales a las canciones (que no empiecen por un número seguido de un punto), o desactivas la maravillosa opción de actualizar los metadatos en el WMP.

Saludos
7553  Programación / Scripting / Re: Suma de variables dentro de bucle for en .bat en: 9 Marzo 2014, 03:06 am
Los parámetros del comando 'Start' los puedes quitar si prefieres, pero, lo usé porque es más práctico para customizar la ejecución de un proceso.

El 'Call' es complétamente necesario para expandir la variable '%%Numero%%', la cual, como puedes ver, lleva 2 pares de '%'.
O usas 'Call', o usas Setlocal EnableDelayedExpansion.

· EnableDelayedExpansion | SS64.com
· Call | SS64.com

Saludos
7554  Seguridad Informática / Seguridad / Re: Desconexion extraña que pensais. en: 9 Marzo 2014, 01:15 am
Será por ingeriería Social no?  >:D


Eso mismo iba a decir yo xDDD

Saludos!
7555  Programación / Scripting / Re: Suma de variables dentro de bucle for en .bat en: 9 Marzo 2014, 00:53 am
esa variable %%x del bucle me confunde

'%%x' es la variable que toma el 'For' para asignar el valor del Rango numérico en el ciclo.

La variable empezará siendo un '1', luego se le asignará un '2', y así sucesívamente hasta llegar a '13' y salir del Loop.

El siguiente código que te muestro, produce el resultado que mencionaste:



Código
  1. @Echo OFF & title Primer programa
  2.  
  3. Set /A "Numero=31"
  4.  
  5. For /L %%X in (1, 1, 13) Do (
  6.  
  7. Set /A "Numero+=1"
  8. Call Start /W "ID3 Maass Tagger" "id3.exe" -1 -2 -t "5.%%X" "%%Numero%%_PISTA.mp3"
  9.  
  10. )
  11.  
  12. Pause&Exit

Saludos
7556  Media / Multimedia / Re: adn de archivos de video para buscar duplicados en: 8 Marzo 2014, 20:07 pm
No, un Hash es (más o menos) un algoritmo criptográfico para calcular un valor que sirve como identificador único de un archivo, basándose en los bytes de dicho archivo,
el Hash no se crea, no es un valor estático (como ya dije, 2 archivos distintos pueden dar como resultado el mismo hash), el Hash es algo que se calcula.

Si intentas grabar metódicamente dos videos iguales con el movil, los fotogramas de uno y del otro nunca van a ser 100% idénticos (movimiento de cámara, particulas de polvo por el aire, la luz del Sol o del entorno, etc)... pero de todas formas, los frames podrían llegar a ser muy parecidos como para poder comparar diferencias y buscar similitudes con un algoritmo en cada fotograma y generar así un porcentaje para determinar si el video se debe considerar como un duplicado o no,
y además, el software de grabación del movil graba en una resolución específica, en un formato determinado, y generarando unos metadatos específicos para ese formato/video, cosas que se pueden comparar con otros videos para identificar videos parecidos o casi iguales.

Como ya dije, no existe un 'ADN' mágico, se utilizan algoritmos de comparación, básicos o avanzados.

Para calcular y comparar Hashes y Checksums te recomiendo la aplicación:

· Object Monitor
  http://sourceforge.net/projects/objectmonitor/

Saludos
7557  Programación / Scripting / Re: [DUDA] Batch o FTP en: 8 Marzo 2014, 19:52 pm
Puedes probar a usar la carpeta temporal del SO, en la cual deberías tener suficientes permisos para escribir:

Código
  1. outFile = CreateObject("WScript.Shell").ExpandEnvironmentStrings( "%TEMP%" & "\" & "IP.txt" )

Saludos
7558  Media / Multimedia / Re: adn de archivos de video para buscar duplicados en: 8 Marzo 2014, 18:22 pm
Si por ADN te refieres a una palabra mágica que te diga si dos videos son iguales al instante entonces NO, no existe ningún 'ADN' mágico que te diga si dos archivos de video son iguales.


Para determinar si un archivo multimedia es idéntico a otro se utilizan métodos de comparación, entre los cuales ahora mismo se me ocurren algunos de menor a mayor dificultad (según mi criterio), y lo mejor es usar una combinación de todos los métodos que se te ocurran ...para mayor seguridad:


· Puedes calcular y comparar el Checksum (CRC32), o un Hash (SHA1, MD5) de 2 archivo de video,
  si dos Hashes coinciden, en teoría se trata del mismo video duplicado;
  Aunque hay muchas cosas a tener en cuenta aquí (si cambias un byte en los metadatos del archivo seguirá siendo el mismo archivo de video pero dará distinto Hash),
  y un video puede dar el mismo Hash que otro que no sea igual, aunque las posibilidades de que esto ocurra son ínfimas,
  pero bueno, este método es el más facil, y existen infinidad de herramientas para la comparación de CRC, MD5, etc y en fin buscar duplicados.


· Puedes comparar los metadatos (tags) de un archivo de video, entre los que destacarían el título, el año, la descripción, los codecs utilizado, etc, si dos videos tienen los mismos tags, óbviamente debe tratarse del mismo video.
  Ojo, un video no tiene porque contener Tags, es un archivo multimedia y como cualquier otro archivo multimedia ...los tags se pueden eliminar.
  También hay que tener en cuenta que los tags se pueden modificar, así qu dos videos distintos pueden contener exáctamente todos los Tags iguales.


· Puedes comparar las dimensiones del video (Ancho x Alto), junto a la duración del video, y comparar los fotogramas iniciales y finales con los demás videos, considero esto el método más seguro.


PD: Para identificar archivos de videos duplicados te recomiendo cualquiera de las siguientes aplicaciones:

· Vistanita Duplicate Finder
  http://download.cnet.com/Vistanita-Duplicate-Finder/3000-2248_4-10668209.html

· Duplicate Finder 2009
  http://www.duplicate-finder-pro.com/index.htm


Saludos
7559  Programación / Scripting / Re: No me deja instalar id3 mass tagger en: 8 Marzo 2014, 16:39 pm
Ahora si, gracias, con el source ya te puedo ayudar.

El problema es que la unidad D: no existe y no se puede encontrar, lo más probable es que al reinstalar Windows este te haya modificado la letra de dicha unidad.

Si escribes una unidad que no existe (Ej: "Z:"), precísamente lanza el mismo error que comentaste:

Cita de: CMD
Código:
c:\>Z:

El sistema no puede encontrar el controlador especificado.


Haz la modificación necearia a la letra de la unidad, y para evitar futuros errores te sugiero reemplazar el comando:
Código:
d:

Por este otro:
Código:
PUSHD "D:"  2>NUL || (Echo No existe la unidad & Pause&Exit /B 1)

(óbviamente, como ya digo, debes asignarle la letra de unidad correcta al comando)


Saludos!
7560  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 8 Marzo 2014, 15:41 pm

Un ejemplo de uso muy básico de la librería NCalc ~> http://ncalc.codeplex.com/

Código
  1.        Dim MathExpression As String = "(2 + 3) * 2" ' Result: 10
  2.  
  3.        Dim NCalcExpression As New NCalc.Expression(MathExpression)
  4.  
  5.        MsgBox(NCalcExpression.Evaluate().ToString)





Una forma de comprobar si un archivo es un ensamblado .NET:

Código
  1.    ' Usage Examples:
  2.    '
  3.    ' MsgBox(IsNetAssembly("C:\File.exe"))
  4.    ' MsgBox(IsNetAssembly("C:\File.dll"))
  5.  
  6.    ''' <summary>
  7.    ''' Gets the common language runtime (CLR) version information of the specified file, using the specified buffer.
  8.    ''' </summary>
  9.    ''' <param name="filepath">Indicates the filepath of the file to be examined.</param>
  10.    ''' <param name="buffer">Indicates the buffer allocated for the version information that is returned.</param>
  11.    ''' <param name="buflen">Indicates the size, in wide characters, of the buffer.</param>
  12.    ''' <param name="written">Indicates the size, in bytes, of the returned buffer.</param>
  13.    ''' <returns>System.Int32.</returns>
  14.    <System.Runtime.InteropServices.DllImport("mscoree.dll",
  15.    CharSet:=System.Runtime.InteropServices.CharSet.Unicode)>
  16.    Private Shared Function GetFileVersion(
  17.                      ByVal filepath As String,
  18.                      ByVal buffer As System.Text.StringBuilder,
  19.                      ByVal buflen As Integer,
  20.                      ByRef written As Integer
  21.    ) As Integer
  22.    End Function
  23.  
  24.    ''' <summary>
  25.    ''' Determines whether an exe/dll file is an .Net assembly.
  26.    ''' </summary>
  27.    ''' <param name="File">Indicates the exe/dll file to check.</param>
  28.    ''' <returns><c>true</c> if file is an .Net assembly; otherwise, <c>false</c>.</returns>
  29.    Public Shared Function IsNetAssembly(ByVal [File] As String) As Boolean
  30.  
  31.        Dim sb = New System.Text.StringBuilder(256)
  32.        Dim written As Integer = 0
  33.        Dim hr = GetFileVersion([File], sb, sb.Capacity, written)
  34.        Return hr = 0
  35.  
  36.    End Function





Un simple efecto de máquina de escribir:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 03-08-2014
  4. ' ***********************************************************************
  5. ' <copyright file="TypeWritter.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Sub Main()
  13.  
  14. '    Console.WriteLine()
  15. '    TypeWritter.WriteLine("[ Typewritter ] - By Elektro")
  16. '    TypeWritter.WriteLine()
  17. '    TypeWritter.WriteLine()
  18. '    TypeWritter.WriteLine("Hola a todos!, les presento este humilde y simple efecto de máquina de escribir")
  19. '    TypeWritter.WriteLine()
  20. '    TypeWritter.WriteLine("Si os fijais aténtamente, quizás ya habreis notado, que hay pausas realistas,   al escribir signos de puntuación...")
  21. '    TypeWritter.WriteLine()
  22. '    TypeWritter.WriteLine("[+] Podemos establecer la velocidad de escritura, por ejemplo, a 20 ms. :")
  23. '    TypeWritter.WriteLine("abcdefghijklmnopqrstuvwxyz", 20)
  24. '    TypeWritter.WriteLine()
  25. '    TypeWritter.WriteLine("[+] Podemos establecer la velocidad de las pausas, por ejemplo, a 2 seg. :")
  26. '    TypeWritter.WriteLine(".,;:", , 2 * 1000)
  27. '    TypeWritter.WriteLine()
  28. '    TypeWritter.WriteLine("[+] El efecto corre en una tarea asíncrona, por lo que se pueden hacer otras cosas mientras tanto, sin frezzear una GUI, y también podemos cancelar la escritura en cualquier momento, gracias al Token de cancelación.")
  29. '    TypeWritter.WriteLine()
  30. '    TypeWritter.WriteLine()
  31. '    TypeWritter.WriteLine("Esto es todo por ahora.")
  32. '    Console.ReadKey()
  33.  
  34. 'End Sub
  35.  
  36. #End Region
  37.  
  38. #Region " TypeWritter "
  39.  
  40. ''' <summary>
  41. ''' Simulates text-typying effect like a Typewritter.
  42. ''' </summary>
  43. Public Class TypeWritter
  44.  
  45. #Region " Properties "
  46.  
  47.    ''' <summary>
  48.    ''' When set to 'True', the running 'Typewritter' task will be cancelled.
  49.    ''' ( The property is set again to 'False' automatically after a 'Task' is cancelled )
  50.    ''' </summary>
  51.    Public Shared Property RequestCancel As Boolean = False
  52.  
  53. #End Region
  54.  
  55. #Region " Task Objects "
  56.  
  57.    ''' <summary>
  58.    ''' The typewritter asynchronous Task.
  59.    ''' </summary>
  60.    Private Shared TypeWritterTask As Threading.Tasks.Task
  61.  
  62.    ''' <summary>
  63.    ''' The typewritter Task Cancellation TokenSource.
  64.    ''' </summary>
  65.    Private Shared TypeWritterTaskCTS As New Threading.CancellationTokenSource
  66.  
  67.    ''' <summary>
  68.    ''' The typewritter Task Cancellation Token.
  69.    ''' </summary>
  70.    Private Shared TypeWritterTaskCT As Threading.CancellationToken = TypeWritterTaskCTS.Token
  71.  
  72. #End Region
  73.  
  74. #Region " Private Methods "
  75.  
  76.    ''' <summary>
  77.    ''' Writes text simulating a Typewritter effect.
  78.    ''' </summary>
  79.    ''' <param name="CancellationToken">Indicates the cancellation token of the Task.</param>
  80.    ''' <param name="Text">Indicates the text to type.</param>
  81.    ''' <param name="TypeSpeed">Indicates the typying speed, in ms.</param>
  82.    ''' <param name="PauseDuration">Indicates the pause duration of the punctuation characters, in ms.</param>
  83.    Private Shared Sub TypeWritter(ByVal CancellationToken As Threading.CancellationToken,
  84.                            ByVal [Text] As String,
  85.                            ByVal TypeSpeed As Integer,
  86.                            ByVal PauseDuration As Integer)
  87.  
  88.        ' If Text is empty then write an empty line...
  89.        If String.IsNullOrEmpty([Text]) Then
  90.  
  91.            ' If not cancellation is already requested then...
  92.            If Not CancellationToken.IsCancellationRequested Then
  93.  
  94.                ' Write an empty line.
  95.                Console.WriteLine()
  96.  
  97.                ' Wait-Speed (empty line).
  98.                Threading.Thread.Sleep(PauseDuration)
  99.  
  100.            End If ' CancellationToken.IsCancellationRequested
  101.  
  102.        End If ' String.IsNullOrEmpty([Text])
  103.  
  104.        ' For each Character in Text to type...
  105.        For Each c As Char In [Text]
  106.  
  107.            ' If not cancellation is already requested then...
  108.            If Not CancellationToken.IsCancellationRequested Then
  109.  
  110.                ' Type the character.
  111.                Console.Write(CStr(c))
  112.  
  113.                ' Type-Wait.
  114.                Threading.Thread.Sleep(TypeSpeed)
  115.  
  116.                If ".,;:".Contains(c) Then
  117.                    ' Pause-Wait.
  118.                    Threading.Thread.Sleep(PauseDuration)
  119.                End If
  120.  
  121.            Else ' want to cancel.
  122.  
  123.                ' Exit iteration.
  124.                Exit For
  125.  
  126.            End If ' CancellationToken.IsCancellationRequested
  127.  
  128.        Next c ' As Char In [Text]
  129.  
  130.    End Sub
  131.  
  132. #End Region
  133.  
  134. #Region " Public Methods "
  135.  
  136.    ''' <summary>
  137.    ''' Writes text simulating a Typewritter effect.
  138.    ''' </summary>
  139.    ''' <param name="Text">Indicates the text to type.</param>
  140.    ''' <param name="TypeSpeed">Indicates the typying speed, in ms.</param>
  141.    ''' <param name="PauseDuration">Indicates the pause duration of the punctuation characters, in ms.</param>
  142.    Public Shared Sub Write(ByVal [Text] As String,
  143.                            Optional ByVal TypeSpeed As Integer = 75,
  144.                            Optional ByVal PauseDuration As Integer = 400)
  145.  
  146.        ' Run the asynchronous Task.
  147.        TypeWritterTask = Threading.Tasks.
  148.                   Task.Factory.StartNew(Sub()
  149.                                             TypeWritter(TypeWritterTaskCT, [Text], TypeSpeed, PauseDuration)
  150.                                         End Sub, TypeWritterTaskCT)
  151.  
  152.        ' Until Task is not completed or is not cancelled, do...
  153.        Do Until TypeWritterTask.IsCompleted OrElse TypeWritterTask.IsCanceled
  154.  
  155.            ' If want to cancel then...
  156.            If RequestCancel Then
  157.  
  158.                ' If not cancellation is already requested then...
  159.                If Not TypeWritterTaskCTS.IsCancellationRequested Then
  160.  
  161.                    ' Cancel the Task.
  162.                    TypeWritterTaskCTS.Cancel()
  163.  
  164.                    ' Renew the cancellation token and tokensource.
  165.                    TypeWritterTaskCTS = New Threading.CancellationTokenSource
  166.                    TypeWritterTaskCT = TypeWritterTaskCTS.Token
  167.  
  168.                End If
  169.  
  170.                ' Reset the cancellation flag var.
  171.                RequestCancel = False
  172.  
  173.                ' Exit iteration.
  174.                Exit Do
  175.  
  176.            End If
  177.  
  178.        Loop ' TypeTask.IsCompleted OrElse TypeTask.IsCanceled
  179.  
  180.    End Sub
  181.  
  182.    ''' <summary>
  183.    ''' Writes text simulating a Typewritter effect, and adds a break-line at the end.
  184.    ''' </summary>
  185.    ''' <param name="Text">Indicates the text to type.</param>
  186.    ''' <param name="TypeSpeed">Indicates the typying speed, in ms.</param>
  187.    ''' <param name="PauseDuration">Indicates the pause duration of the punctuation characters, in ms.</param>
  188.    Public Shared Sub WriteLine(ByVal [Text] As String,
  189.                                Optional ByVal TypeSpeed As Integer = 75,
  190.                                Optional ByVal PauseDuration As Integer = 400)
  191.  
  192.        Write([Text], TypeSpeed, PauseDuration)
  193.        Console.WriteLine()
  194.  
  195.    End Sub
  196.  
  197.    ''' <summary>
  198.    ''' Writes an empty line.
  199.    ''' </summary>
  200.    ''' <param name="PauseDuration">Indicates the pause duration of the empty line, in ms.</param>
  201.    Public Shared Sub WriteLine(Optional ByVal PauseDuration As Integer = 750)
  202.  
  203.        Write(String.Empty, 1, PauseDuration)
  204.  
  205.    End Sub
  206.  
  207. #End Region
  208.  
  209. End Class
  210.  
  211. #End Region
Páginas: 1 ... 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 [756] 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 ... 1258
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines