Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - Eleкtro

#511
Cita de: Meta en 20 Febrero 2019, 21:22 PM
No esperaba que usaras el kernel32.dll.

...¿y eso lo dices por el último código que he compartido?. Sin comentarios. Si cuando digo que una persona no lee nada de lo que le muestran, es por que tengo razón...

Un saludo
#512
Bueno, al final he decidido mejorarlo para extender la funcionalidad y crear un par de funciones reutilizables, aparte de que ahora el algoritmo preserva tanto el color de texto como el color de fondo, y he corregido un error que había en el primer código con respecto a la posición donde se escriben los caracteres...

Código (vbnet) [Seleccionar]
Public NotInheritable Class Native

   Private Sub New()
   End Sub

   <DllImport("kernel32.dll", SetLastError:=True)>
   Public Shared Function GetStdHandle(ByVal std As ConsoleStd
   ) As IntPtr
   End Function

   <DllImport("kernel32.dll", SetLastError:=True)>
   Public Shared Function ReadConsoleOutput(ByVal consoleOutput As IntPtr,
                                            ByVal buffer As IntPtr,
                                            ByVal bufferSize As ConsoleCoordinate,
                                            ByVal bufferCoord As ConsoleCoordinate,
                                            ByRef refReadRegion As NativeRectangleSmall
   ) As <MarshalAs(UnmanagedType.Bool)> Boolean
   End Function

   <StructLayout(LayoutKind.Sequential)>
   Public Structure CharInfo ' CHAR_INFO
       <MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)>
       Public CharData As Byte()
       <MarshalAs(UnmanagedType.I2)>
       Public Attributes As CharInfoAttributes
   End Structure

   <StructLayout(LayoutKind.Sequential)>
   Public Structure ConsoleCoordinate ' COORD
       Public X As Short
       Public Y As Short
   End Structure

   <StructLayout(LayoutKind.Sequential)>
   Public Structure NativeRectangleSmall ' SMALL_RECT
       Public Left As Short
       Public Top As Short
       Public Right As Short
       Public Bottom As Short
   End Structure

   Public Enum ConsoleStd As Integer
       StandardInput = -10
       StandardOutput = -11
       StandardError = -12
   End Enum

   <Flags>
   Public Enum CharInfoAttributes As Short
       None = &H0S ' Black Color
       BlackColor = CharInfoAttributes.None
       ForeColorBlue = &H1S
       ForeColorGreen = &H2S
       ForeColorRed = &H4S
       ForeColorIntensity = &H8S
       BackColorBlue = &H10S
       BackColorGreen = &H20S
       BackColorRed = &H40S
       BackColorIntensity = &H80S
       LeadingByte = &H100S
       TrailingByte = &H200S
       GridHorizontal = &H400S
       GridVerticalLeft = &H800S
       GridVerticalRight = &H1000S
       ReverseVideo = &H4000S
       Underscore = &H8000S
       ForeColorMask = CharInfoAttributes.ForeColorBlue Or
                       CharInfoAttributes.ForeColorGreen Or
                       CharInfoAttributes.ForeColorRed Or
                       CharInfoAttributes.ForeColorIntensity
       BackColorMask = CharInfoAttributes.BackColorBlue Or
                       CharInfoAttributes.BackColorGreen Or
                       CharInfoAttributes.BackColorRed Or
                       CharInfoAttributes.BackColorIntensity
       ColorMask = CharInfoAttributes.ForeColorMask Or
                   CharInfoAttributes.BackColorMask
   End Enum

End Class


Código (vbnet) [Seleccionar]
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Blinks the specified text for the specified amount of times on the current attached console window.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example.
''' <code>
''' Dim pos As New Point(10, 2)
''' Dim str As String = "Hello World!"
'''
''' Console.SetCursorPosition(pos.X, pos.Y)
''' Console.Write(str)
'''
''' ' Start blinking the text written.
''' Dim len As Integer = str.Length
''' Dim interval As Integer = 500
''' Dim count As Integer = 10
''' ConsoleTextBlink(pos, len, interval, count)
'''
''' ' Terminate program.
''' Console.ReadKey(intercept:=False)
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
''' <param name="position">
''' A <see cref="System.Drawing.Point"/> that indicates the start position of the text.
''' <para></para>
''' <see cref="System.Drawing.Point.X"/> specifies the column, <see cref="System.Drawing.Point.Y"/> the row.
''' </param>
'''
''' <param name="length">
''' The length of the text (or cells) to blink.
''' </param>
'''
''' <param name="interval">
''' The blink interval, in milliseconds.
''' </param>
'''
''' <param name="count">
''' The amount of times to blink the text.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' A <see cref="CancellationTokenSource"/> object which you can use it to stop the blink at any time.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Function ConsoleTextBlink(ByVal position As Point, ByVal length As Integer, ByVal interval As Integer, count As Integer) As CancellationTokenSource
    Return InternalConsoleTextBlink(position, length, TimeSpan.FromMilliseconds(interval), count)
End Function

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Blinks the specified text for the specified amount of times on the current attached console window.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example.
''' <code>
''' Dim pos As New Point(10, 2)
''' Dim str As String = "Hello World!"
'''
''' Console.SetCursorPosition(pos.X, pos.Y)
''' Console.Write(str)
'''
''' ' Start blinking the text written.
''' Dim len As Integer = str.Length
''' Dim interval As TimeSpan = TimeSpan.FromMilliseconds(500)
''' Dim count As Integer = 10
''' ConsoleTextBlink(pos, len, interval, count)
'''
''' ' Terminate program.
''' Console.ReadKey(intercept:=False)
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
''' <param name="position">
''' A <see cref="System.Drawing.Point"/> that indicates the start position of the text.
''' <para></para>
''' <see cref="System.Drawing.Point.X"/> specifies the column, <see cref="System.Drawing.Point.Y"/> the row.
''' </param>
'''
''' <param name="length">
''' The length of the text (or cells) to blink.
''' </param>
'''
''' <param name="interval">
''' The blink interval.
''' </param>
'''
''' <param name="count">
''' The amount of times to blink the text.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' A <see cref="CancellationTokenSource"/> object which you can use it to stop the blink at any time.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Function ConsoleTextBlink(ByVal position As Point, ByVal length As Integer, ByVal interval As TimeSpan, count As Integer) As CancellationTokenSource
    Return InternalConsoleTextBlink(position, length, interval, count)
End Function

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Blinks the specified text for indefinitely time on the current attached console window.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example.
''' <code>
''' Dim pos As New Point(10, 2)
''' Dim str As String = "Hello World!"
'''
''' Console.SetCursorPosition(pos.X, pos.Y)
''' Console.Write(str)
'''
''' ' Start blinking the text written.
''' Dim len As Integer = str.Length
''' Dim interval As Integer = 500
''' Dim blinkCt As CancellationTokenSource = ConsoleTextBlink(pos, len, interval)
'''
''' ' Stop blinking after 5 seconds elapsed.
''' blinkCt.CancelAfter(5000)
'''
''' ' Terminate program.
''' Console.ReadKey(intercept:=False)
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
''' <param name="position">
''' A <see cref="System.Drawing.Point"/> that indicates the start position of the text.
''' <para></para>
''' <see cref="System.Drawing.Point.X"/> specifies the column, <see cref="System.Drawing.Point.Y"/> the row.
''' </param>
'''
''' <param name="length">
''' The length of the text (or cells) to blink.
''' </param>
'''
''' <param name="interval">
''' The blink interval, in milliseconds.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' A <see cref="CancellationTokenSource"/> object which you can use it to stop the blink at any time.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Function ConsoleTextBlink(ByVal position As Point, ByVal length As Integer, ByVal interval As Integer) As CancellationTokenSource
    Return InternalConsoleTextBlink(position, length, TimeSpan.FromMilliseconds(interval), Integer.MaxValue)
End Function

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Blinks the specified text for indefinitely time on the current attached console window.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example.
''' <code>
''' Dim pos As New Point(10, 2)
''' Dim str As String = "Hello World!"
'''
''' Console.SetCursorPosition(pos.X, pos.Y)
''' Console.Write(str)
'''
''' ' Start blinking the text written.
''' Dim len As Integer = str.Length
''' Dim interval As TimeSpan = TimeSpan.FromMilliseconds(500)
''' Dim blinkCt As CancellationTokenSource = ConsoleTextBlink(pos, len, interval)
''' blinkCt.CancelAfter()
'''
''' ' Stop blinking after 5 seconds elapsed.
''' blinkCt.CancelAfter(5000)
'''
''' ' Terminate program.
''' Console.ReadKey(intercept:=False)
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
''' <param name="position">
''' A <see cref="System.Drawing.Point"/> that indicates the start position of the text.
''' <para></para>
''' <see cref="System.Drawing.Point.X"/> specifies the column, <see cref="System.Drawing.Point.Y"/> the row.
''' </param>
'''
''' <param name="length">
''' The length of the text (or cells) to blink.
''' </param>
'''
''' <param name="interval">
''' The blink interval.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' A <see cref="CancellationTokenSource"/> object which you can use it to stop the blink at any time.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Function ConsoleTextBlink(ByVal position As Point, ByVal length As Integer, ByVal interval As TimeSpan) As CancellationTokenSource
    Return InternalConsoleTextBlink(position, length, interval, Integer.MaxValue)
End Function

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Blinks the specified text for the specified amount of times on the current attached console window.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="position">
''' A <see cref="System.Drawing.Point"/> that indicates the start position of the text.
''' <para></para>
''' <see cref="System.Drawing.Point.X"/> specifies the column, <see cref="System.Drawing.Point.Y"/> the row.
''' </param>
'''
''' <param name="length">
''' The length of the text (or cells) to blink.
''' </param>
'''
''' <param name="interval">
''' The blink interval.
''' </param>
'''
''' <param name="count">
''' The amount of times to blink the text.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' A <see cref="CancellationTokenSource"/> object which you can use it to stop the blink at any time.
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Private Function InternalConsoleTextBlink(ByVal position As Point, ByVal length As Integer, ByVal interval As TimeSpan, ByVal count As Integer) As CancellationTokenSource

    If (count <= 0) Then
        Throw New ArgumentException(paramName:=NameOf(count), message:="Value greater than 0 is required.")
    End If

    If (interval.TotalMilliseconds <= 0) Then
        Throw New ArgumentException(paramName:=NameOf(interval), message:="Value greater than 0 is required.")
    End If

    Dim cts As New CancellationTokenSource()

    Dim t As New Task(
        Sub()
            Dim x As Short = CShort(position.X)
            Dim y As Short = CShort(position.Y)
            Dim width As Short = CShort(length)
            Dim height As Short = 1S
            Dim buffer As IntPtr = Marshal.AllocHGlobal(width * height * Marshal.SizeOf(GetType(Native.CharInfo)))
            Dim blinkCount As Integer

            Try
                Dim bufferCoord As New Native.ConsoleCoordinate()
                Dim bufferSize As New Native.ConsoleCoordinate With {
                    .X = width,
                    .Y = height
                }

                Dim rc As New Native.NativeRectangleSmall With {
                    .Left = x,
                    .Top = y,
                    .Right = (x + width - 1S),
                    .Bottom = (y + height - 1S)
                }

                Dim stdOutHandle As IntPtr = Native.GetStdHandle(Native.ConsoleStd.StandardOutput)
                If Not Native.ReadConsoleOutput(stdOutHandle, buffer, bufferSize, bufferCoord, rc) Then
                    ' Not enough storage is available to process this command' may be raised for buffer size > 64K (see ReadConsoleOutput doc.)
                    Throw New Win32Exception(Marshal.GetLastWin32Error())
                End If

                Dim charInfoList As New List(Of Native.CharInfo)
                Dim ptr As IntPtr = buffer
                For heightIndex As Integer = 0 To (height - 1)
                    For widthIndex As Integer = 0 To (width - 1)
                        Dim ci As Native.CharInfo = DirectCast(Marshal.PtrToStructure(ptr, GetType(Native.CharInfo)), Native.CharInfo)
                        charInfoList.Add(ci)
                        ptr += Marshal.SizeOf(GetType(Native.CharInfo))
                    Next widthIndex
                Next heightIndex

                Do Until cts.Token.IsCancellationRequested
                    Dim oldCursorVisible As Boolean = Console.CursorVisible
                    Dim oldPos As New Point(Console.CursorLeft, Console.CursorTop)
                    Dim oldBackColor As ConsoleColor = Console.BackgroundColor
                    Dim oldForeColor As ConsoleColor = Console.ForegroundColor

                    Console.CursorVisible = False
                    Console.SetCursorPosition(position.X, position.Y)
                    Console.Write(New String(" "c, length))
                    Console.CursorVisible = oldCursorVisible
                    Console.SetCursorPosition(oldPos.X, oldPos.Y)
                    Thread.Sleep(interval)
                    Console.CursorVisible = False

                    For i As Integer = 0 To (charInfoList.Count - 1)
                        Dim ci As Native.CharInfo = charInfoList(i)
                        Dim chars As Char() = (From c As Char In Console.OutputEncoding.GetChars(ci.CharData)
                                               Where (c <> Nothing)).ToArray()

                        Dim foreColor As ConsoleColor
                        If ((ci.Attributes And Native.CharInfoAttributes.ForeColorMask) <> 0) Then
                            foreColor = CType((CInt(ci.Attributes)) And Not Native.CharInfoAttributes.BackColorMask, ConsoleColor)
                        End If

                        Dim backColor As ConsoleColor
                        If ((ci.Attributes And Native.CharInfoAttributes.BackColorMask) <> 0) Then
                            ' Turn background colors into foreground colors.
                            ' https://referencesource.microsoft.com/#mscorlib/system/console.cs,7a88edaade340cdb
                            backColor = CType((CInt(ci.Attributes)) >> 4, ConsoleColor)
                        End If

                        Console.SetCursorPosition((position.X + i), position.Y)
                        Console.ForegroundColor = foreColor
                        Console.BackgroundColor = backColor
                        Console.Write(chars)
                    Next i

                    Console.SetCursorPosition(oldPos.X, oldPos.Y)
                    Console.CursorVisible = oldCursorVisible
                    Console.ForegroundColor = oldForeColor
                    Console.BackgroundColor = oldBackColor

                    If Interlocked.Increment(blinkCount) = count Then
                        If (cts.Token.CanBeCanceled) Then
                            cts.Cancel()
                        End If
                        Exit Do
                    End If
                    Thread.Sleep(interval)
                Loop

            Finally
                Marshal.FreeHGlobal(buffer)

            End Try

        End Sub, cts.Token)

    t.Start()
    Return cts

End Function


Modo de empleo:

Código (vbnet) [Seleccionar]
Dim pos As New Point(10, 2)
Dim str As String = "Hello World!"

Console.SetCursorPosition(pos.X, pos.Y)
Console.Write(str)

' Start blinking the text written.
Dim len As Integer = str.Length
Dim interval As Integer = 500
Dim count As Integer = 10
ConsoleTextBlink(pos, len, interval, count)

' Terminate program.
Console.ReadKey(intercept:=False)


O bien...
Código (vbnet) [Seleccionar]
Dim pos As New Point(10, 2)
Dim str As String = "Hello World!"

Console.SetCursorPosition(pos.X, pos.Y)
Console.Write(str)

' Start blinking the text written.
Dim len As Integer = str.Length
Dim interval As TimeSpan = TimeSpan.FromMilliseconds(500)
Dim blinkCt As CancellationTokenSource = ConsoleTextBlink(pos, len, interval)

' Stop blinking after 5 seconds elapsed.
blinkCt.CancelAfter(5000)

' Terminate program.
Console.ReadKey(intercept:=False)

#513
Cita de: boshide10 en 20 Febrero 2019, 06:48 AM
Ok y como modifico el nivel de porcentaje por ej si quiero tener el cpu al 95%
y como unifico eso para que el disco la ram y la cpu esten consumiendo por lo menos mas del 85% a la ves ?.

Si te refieres a mi código fuente, para "unificarlo" solo tienes que instanciar las 3 clases al mismo tiempo y llamar a su método Allocate() (si quieres unificar el código fuente, también se puede pero obviamente requiere varias modificaciones), y para cambiar el porcentaje de CPU es suficiente con que leas el código de ejemplo que mostré para ello...

Saludos.
#514
Cita de: Meta en  9 Febrero 2019, 17:12 PM
No me gusta el código de arriba, mejor el que dices.

Iba a tirar el código pero antes de tirarlo lo comparto aquí. El código está sin optimizar lo suficiente, incompleto (solo faltaría por implementar la preservación del color de fondo, el cual se especifica en los flags de estructura CHAR_INFO) y sin documentar...

Por cierto, lo hice en VB.NET, así que necesitarás usar cualquier conversor de código a C#.

Código (vbnet) [Seleccionar]
Friend NotInheritable Class NativeMethods

   <StructLayout(LayoutKind.Sequential)>
   Friend Structure CHAR_INFO
       <MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)>
       Public charData() As Byte
       Public attributes As Short
   End Structure

   <StructLayout(LayoutKind.Sequential)>
   Friend Structure COORD
       Public X As Short
       Public Y As Short
   End Structure

   <StructLayout(LayoutKind.Sequential)>
   Friend Structure SMALL_RECT
       Public Left As Short
       Public Top As Short
       Public Right As Short
       Public Bottom As Short
   End Structure

   <StructLayout(LayoutKind.Sequential)>
   Friend Structure CONSOLE_SCREEN_BUFFER_INFO
       Public dwSize As COORD
       Public dwCursorPosition As COORD
       Public wAttributes As Short
       Public srWindow As SMALL_RECT
       Public dwMaximumWindowSize As COORD
   End Structure

   <DllImport("kernel32.dll", SetLastError:=True)>
   Friend Shared Function ReadConsoleOutput(ByVal consoleOutput As IntPtr,
                                            ByVal buffer As IntPtr,
                                            ByVal bufferSize As COORD,
                                            ByVal bufferCoord As COORD,
                                            ByRef refReadRegion As SMALL_RECT) As Boolean
   End Function

   <DllImport("kernel32.dll", SetLastError:=True)>
   Friend Shared Function GetStdHandle(ByVal stdHandle As Integer) As IntPtr
   End Function

End Class


Código (vbnet) [Seleccionar]
Public Shared Function ConsoleBlink(ByVal position As Point, ByVal length As Integer, ByVal interval As TimeSpan) As CancellationTokenSource

   Dim cts As New CancellationTokenSource()

   Const STD_OUTPUT_HANDLE As Integer = -11

   Dim t As New Task(
       Sub()

           Dim x As Short = CShort(position.X)
           Dim y As Short = CShort(position.Y)
           Dim width As Short = CShort(length)
           Dim height As Short = 1S
           Dim buffer As IntPtr = Marshal.AllocHGlobal(width * height * Marshal.SizeOf(GetType(CHAR_INFO)))

           Try
               Dim bufferCoord As New COORD()
               Dim bufferSize As New COORD With {
                   .X = width,
                   .Y = height
               }

               Dim rc As New SMALL_RECT With {
                   .Left = x,
                   .Top = y,
                   .Right = (x + width - 1S),
                   .Bottom = (y + height - 1S)
               }

               Dim stdOutHandle As IntPtr = NativeMethods.GetStdHandle(STD_OUTPUT_HANDLE)
               If Not NativeMethods.ReadConsoleOutput(stdOutHandle, buffer, bufferSize, bufferCoord, rc) Then
                   ' Not enough storage is available to process this command' may be raised for buffer size > 64K (see ReadConsoleOutput doc.)
                   Throw New Win32Exception(Marshal.GetLastWin32Error())
               End If

               Dim charInfoList As New List(Of CHAR_INFO)
               Dim ptr As IntPtr = buffer
               For h As Integer = 0 To (height - 1)
                   For w As Integer = 0 To (width - 1)
                       Dim ci As CHAR_INFO = DirectCast(Marshal.PtrToStructure(ptr, GetType(CHAR_INFO)), CHAR_INFO)
                       charInfoList.Add(ci)
                       ptr += Marshal.SizeOf(GetType(CHAR_INFO))
                   Next w
               Next h

               Do Until cts.Token.IsCancellationRequested
                   Dim oldCursorVisible As Boolean = Console.CursorVisible
                   Dim oldPos As New Point(Console.CursorLeft, Console.CursorTop)
                   Dim oldBackColor As ConsoleColor = Console.BackgroundColor
                   Dim oldForeColor As ConsoleColor = Console.ForegroundColor

                   Console.CursorVisible = False
                   Console.SetCursorPosition(position.X, position.Y)
                   Console.Write(New String(" "c, length))
                   Console.CursorVisible = oldCursorVisible
                   Console.SetCursorPosition(oldPos.X, oldPos.Y)
                   Thread.Sleep(interval)
                   Console.CursorVisible = False

                   For i As Integer = 0 To (charInfoList.Count - 1)
                       Dim ci As CHAR_INFO = charInfoList(i)
                       Dim chars As Char() = Console.OutputEncoding.GetChars(ci.charData)
                       Dim color As ConsoleColor = CType(ci.attributes, ConsoleColor)

                       Console.SetCursorPosition(i, position.Y)
                       Console.ForegroundColor = color
                       Console.Write(chars)
                   Next

                   Console.SetCursorPosition(oldPos.X, oldPos.Y)
                   Console.CursorVisible = oldCursorVisible
                   Console.ForegroundColor = oldForeColor
                   Thread.Sleep(interval)
               Loop

           Finally
               Marshal.FreeHGlobal(buffer)

           End Try

       End Sub, cts.Token)

   t.Start()
   Return cts

End Function


Modo de empleo:
Código (vbnet) [Seleccionar]
Public Module Module1

   Public Sub Main()

       Dim tt As New Timers.Timer

       Console.WindowWidth = 20
       Console.WindowHeight = 5
       Console.CursorVisible = False
       Console.ReadKey()

       Dim blinkStr1 As String = "Test"
       Dim blinkPos1 As New Point(0, 0)
       Dim blinkLen1 As Integer = blinkStr1.Length
       Dim blinkTime1 As TimeSpan = TimeSpan.FromMilliseconds(500)
       Dim blinkCt1 As CancellationTokenSource

       Dim blinkStr2 As String = "Test"
       Dim blinkPos2 As New Point(0, 1)
       Dim blinkLen2 As Integer = blinkStr2.Length
       Dim blinkTime2 As TimeSpan = TimeSpan.FromMilliseconds(100)
       Dim blinkCt2 As CancellationTokenSource

       ' Manually write the blink string at the first console row.
       Console.SetCursorPosition(blinkPos1.X, blinkPos1.Y)
       Console.ForegroundColor = ConsoleColor.Yellow
       Console.Write(blinkStr1(0))
       Console.ForegroundColor = ConsoleColor.Cyan
       Console.Write(blinkStr1(1))
       Console.ForegroundColor = ConsoleColor.Green
       Console.Write(blinkStr1(2))
       Console.ForegroundColor = ConsoleColor.Red
       Console.Write(blinkStr1(3))
       Console.ForegroundColor = ConsoleColor.White

       ' Manually write the blink string at the second console row.
       Console.SetCursorPosition(blinkPos2.X, blinkPos2.Y)
       Console.ForegroundColor = ConsoleColor.Green
       Console.Write(blinkStr2)

       ' Start blinking the text and return the task cancellation token sources.
       blinkCt1 = ConsoleBlink(blinkPos1, blinkLen1, blinkTime1)
       blinkCt2 = ConsoleBlink(blinkPos2, blinkLen2, blinkTime2)

       ' Write another string.
       Console.ForegroundColor = ConsoleColor.White
       Console.SetCursorPosition(0, 2)
       Console.Write("Hello World!")

       ' Wait 5 seconds and cancel text blinking.
       Thread.Sleep(TimeSpan.FromSeconds(5))
       Dim t As New Task(
           Sub()
               blinkCt1.Cancel()
               blinkCt2.Cancel()
           End Sub)
       t.Start()

       Console.Read()

   End Sub

End Module
#515
Generador aleatorio de párrafos

Código (vbnet) [Seleccionar]
Private Shared rng As New Random(Seed:=Environment.TickCount)

Código (vbnet) [Seleccionar]
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Generates a random paragraph using the specified set of words.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="words">
''' The words that will be used to build paragraphs.
''' </param>
'''
''' <param name="numberOfParagraphs">
''' The number of paragraphs to generate.
''' </param>
'''
''' <param name="htmlFormatting">
''' Specifies whether or not to format paragraphs for HTML.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The resulting paragraph(s).
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Shared Function RandomParagraphGenerator(ByVal words As String(),
                                               ByVal numberOfParagraphs As Integer,
                                               ByVal htmlFormatting As Boolean) As String

   Dim sb As New StringBuilder()

   Dim nextWord As String
   Dim nextWordIndex As Integer
   Dim lastWordIndex As Integer

   For paragraphIndex As Integer = 0 To (numberOfParagraphs - 1)

       Dim phraseLen As Integer = rng.Next(2, 10)
       For phraseIndex As Integer = 0 To (phraseLen - 1)

           If (phraseIndex = 0) AndAlso (htmlFormatting) Then
               sb.Append("<p>")
           End If

           Dim wordLen As Integer = rng.Next(3, 15)
           Dim addComma As Boolean = (rng.NextDouble() < 50 / 100.0) ' 50% probability to add a comma in a phrase.
           Dim commaAmount As Integer = rng.Next(1, (wordLen - 1) \ 2)
           Dim commaIndices As New HashSet(Of Integer)
           For i As Integer = 0 To (commaAmount - 1)
               commaIndices.Add(rng.Next(1, (wordLen - 1)))
           Next i

           For wordIndex As Integer = 0 To (wordLen - 1)

               Do Until (nextWordIndex <> lastWordIndex)
                   nextWordIndex = rng.Next(0, words.Length)
               Loop
               lastWordIndex = nextWordIndex
               nextWord = words(nextWordIndex)

               If (wordIndex = 0) Then
                   sb.Append(Char.ToUpper(nextWord(0)) & nextWord.Substring(1))
                   Continue For
               End If
               sb.Append(" " & words(rng.Next(0, words.Length)))

               If (commaIndices.Contains(wordIndex)) AndAlso (addComma) Then
                   sb.Append(","c)
               End If

               If (wordIndex = (wordLen - 1)) Then
                   If (phraseIndex <> (phraseLen - 1)) Then
                       sb.Append(". ")
                   Else
                       sb.Append(".")
                   End If
               End If
           Next wordIndex

       Next phraseIndex

       If (htmlFormatting) Then
           sb.Append("</p>")
       End If

       sb.AppendLine(Environment.NewLine)

   Next paragraphIndex

   Return sb.ToString()
End Function


Modo de empleo:
Código (vbnet) [Seleccionar]
Dim words As String() = {
   "a", "ability", "able", "about", "above", "accept", "according", "account", "across",
   "act", "action", "activity", "actually", "add", "address", "administration", "admit",
   "adult", "affect", "after", "again", "against", "age", "agency", "agent", "ago", "agree",
   "agreement", "ahead", "air", "all", "allow", "almost", "alone", "along", "already", "also",
   "although", "always", "American", "among", "amount", "analysis", "and", "animal", "another",
   "answer", "any", "anyone", "anything", "appear", "apply", "approach", "area", "argue", "arm",
   "around", "arrive", "art", "article", "artist", "as", "ask", "assume", "at", "attack", "attention",
   "attorney", "audience", "author", "authority", "available", "avoid", "away", "baby", "back",
   "bed", "before", "begin", "behavior", "behind", "believe", "benefit", "best", "better", "between",
   "both", "box", "boy", "break", "bring", "brother", "budget", "build", "building", "business", "but",
   "buy", "by", "call", "camera", "campaign", "can", "cancer", "candidate", "capital", "car", "card",
   "care", "career", "carry", "case", "catch", "cause", "cell", "center", "central", "century", "certain",
   "choice", "choose", "church", "citizen", "city", "civil", "claim", "class", "clear", "clearly",
   "close", "coach", "cold", "collection", "college", "color", "come", "commercial", "common", "community",
   "consumer", "contain", "continue", "control", "cost", "could", "country", "couple", "course", "court",
   "cover", "create", "crime", "cultural", "culture", "cup", "current", "customer", "cut", "dark",
   "data", "daughter", "day", "dead", "deal", "death", "debate", "decade", "decide", "decision", "deep",
   "defense", "degree", "Democrat", "democratic", "describe", "design", "despite", "detail",
   "direction", "director", "discover", "discuss", "discussion", "disease", "do", "doctor", "dog",
   "door", "down", "draw", "dream", "drive", "drop", "drug", "during", "each", "early", "east", "easy",
   "eat", "economic", "economy", "edge", "education", "effect", "effort", "eight", "either", "election",
   "environmental", "especially", "establish", "even", "evening", "event", "ever", "every", "everybody",
   "everyone", "everything", "evidence", "exactly", "example", "executive", "exist", "expect",
   "experience", "expert", "explain", "eye", "face", "fact", "factor", "fail", "fall", "family",
   "fill", "film", "final", "finally", "financial", "find", "fine", "finger", "finish", "fire",
   "firm", "first", "fish", "five", "floor", "fly", "focus", "follow", "food", "foot", "for",
   "force", "foreign", "forget", "form", "former", "forward", "four", "free", "friend", "from",
   "front", "full", "fund", "future", "game", "garden", "gas", "general", "generation", "get",
   "girl", "give", "glass", "go", "goal", "good", "government", "great", "green", "ground",
   "group", "grow", "growth", "guess", "gun", "guy", "hair", "half", "hand", "hang", "happen",
   "happy", "hard", "have", "he", "head", "health", "hear", "heart", "heat", "heavy", "help",
   "her", "here", "herself", "high", "him", "himself", "his", "history", "hit", "hold", "home",
   "hope", "hospital", "hot", "hotel", "hour", "house", "how", "however", "huge", "human", "hundred",
   "husband", "I", "idea", "identify", "if", "image", "imagine", "impact", "important", "improve",
   "in", "include", "including", "increase", "indeed", "indicate", "individual", "industry",
   "information", "inside", "instead", "institution", "interest", "interesting", "international",
   "interview", "into", "investment", "involve", "issue", "it", "item", "its", "itself", "job",
   "join", "just", "keep", "key", "kid", "kill", "kind", "kitchen", "know", "knowledge", "land",
   "language", "large", "last", "late", "later", "laugh", "law", "lawyer", "lay", "lead", "leader",
   "learn", "least", "leave", "left", "leg", "legal", "less", "let", "letter", "level", "lie", "life",
   "light", "like", "likely", "line", "list", "listen", "little", "live", "local", "long", "look",
   "lose", "loss", "lot", "love", "low", "machine", "magazine", "main", "maintain", "major", "majority",
   "make", "man", "manage", "management", "manager", "many", "market", "marriage", "material", "matter",
   "may", "maybe", "me", "mean", "measure", "media", "medical", "meet", "meeting", "member",
   "memory", "mention", "message", "method", "middle", "might", "military", "million", "mind",
   "minute", "miss", "mission", "model", "modern", "moment", "money", "month", "more", "morning",
   "most", "mother", "mouth", "move", "movement", "movie", "Mr", "Mrs", "much", "music", "must",
   "my", "myself", "name", "nation", "national", "natural", "nature", "near", "nearly", "necessary",
   "need", "network", "never", "new", "news", "newspaper", "next", "nice", "night", "no", "none", "nor",
   "north", "not", "note", "nothing", "notice", "now", "number", "occur", "of", "off", "offer",
   "office", "officer", "official", "often", "oh", "oil", "ok", "old", "on", "once", "one", "only",
   "onto", "open", "operation", "opportunity", "option", "or", "order", "organization", "other",
   "others", "our", "out", "outside", "over", "own", "owner", "page", "pain", "painting", "paper",
   "parent", "part", "participant", "particular", "particularly", "partner", "party", "pass",
   "past", "patient", "pattern", "pay", "peace", "people", "per", "perform", "performance",
   "perhaps", "period", "person", "personal", "phone", "physical", "pick", "picture",
   "piece", "place", "plan", "plant", "play", "player", "PM", "point", "police", "policy",
   "political", "politics", "poor", "popular", "population", "position", "positive",
   "possible", "power", "practice", "prepare", "present", "president", "pressure",
   "pretty", "prevent", "price", "private", "probably", "problem", "process", "produce",
   "product", "production", "professional", "professor", "program", "project", "property", "protect",
   "prove", "provide", "public", "pull", "purpose", "push", "put", "quality", "question", "quickly",
   "quite", "race", "radio", "raise", "range", "rate", "rather", "reach", "read", "ready", "real",
   "reality", "realize", "really", "reason", "receive", "recent", "recently", "recognize", "record",
   "red", "reduce", "reflect", "region", "relate", "relationship", "religious", "remain", "remember",
   "remove", "report", "represent", "Republican", "require", "research", "resource", "respond", "response",
   "responsibility", "rest", "result", "return", "reveal", "rich", "right", "rise", "risk", "road",
   "rock", "role", "room", "rule", "run", "safe", "same", "save", "say", "scene", "school", "science",
   "scientist", "score", "sea", "season", "seat", "second", "section", "security", "see", "seek",
   "seem", "sell", "send", "senior", "sense", "series", "serious", "serve", "service", "set", "seven",
   "show", "side", "sign", "significant", "similar", "simple", "simply", "since", "sing", "single",
   "sister", "sit", "site", "situation", "six", "size", "skill", "skin", "small", "smile", "so",
   "social", "society", "soldier", "some", "somebody", "someone", "something", "sometimes", "son",
   "specific", "speech", "spend", "sport", "spring", "staff", "stage", "stand", "standard", "star",
   "start", "state", "statement", "station", "stay", "step", "still", "stock", "stop", "store",
   "story", "strategy", "street", "strong", "structure", "student", "study", "stuff", "style",
   "subject", "success", "successful", "such", "suddenly", "suffer", "suggest", "summer", "support",
   "sure", "surface", "system", "table", "take", "talk", "task", "tax", "teach", "teacher", "team",
   "technology", "television", "tell", "ten", "tend", "term", "test", "than", "thank", "that", "the",
   "their", "them", "themselves", "then", "theory", "there", "these", "they", "thing", "think",
   "third", "this", "those", "though", "thought", "thousand", "threat", "three", "through", "throughout",
   "throw", "thus", "time", "to", "today", "together", "tonight", "too", "top", "total", "tough",
   "toward", "town", "trade", "traditional", "training", "travel", "treat", "treatment", "tree",
   "trial", "trip", "trouble", "true", "truth", "try", "turn", "TV", "two", "type", "under", "understand",
   "unit", "until", "up", "upon", "us", "use", "usually", "value", "various", "very", "victim",
   "view", "violence", "visit", "voice", "vote", "wait", "walk", "wall", "want", "war", "watch", "water",
   "way", "we", "weapon", "wear", "week", "weight", "well", "west", "western", "what", "whatever",
   "when", "where", "whether", "which", "while", "white", "who", "whole", "whom", "whose", "why",
   "wide", "wife", "will", "win", "wind", "window", "wish", "with", "within", "without", "woman",
   "wonder", "word", "work", "worker", "world", "worry", "would", "write", "writer", "wrong", "yard",
   "yeah", "year", "yes", "yet", "you", "young", "your", "yourself"}

Dim paragraphs As String = RandomParagraphGenerator(words, numberOfParagraphs:=4, htmlFormatting:=False)
Console.WriteLine(paragraphs)


CitarFinish at, raise, movie exist page, including there, yard ground why, information everyone. Life full those finger instead simple central those scientist. Force road of pick your student social. Prevent plan heart site. Anyone door, explain control.

Process interest we high human occur agree page put. Left education according thus, structure fine second professor rather relationship guess instead maybe radio. Second process reason on, create west. Forget victim wrong may themselves out where occur sometimes. Wide candidate, newspaper, if purpose at assume draw month, American physical create. Sea sign describe white though want minute type to medical. Explain girl their most upon.

Suddenly drug writer follow must. Right choose, option one capital risk. Administration forget practice anything. Notice people take movie, dark, yes only. Inside either recent movement during particular wear husband particularly those legal. Suffer drug establish work. Guess two have garden value property realize dog people friend, hospital that.

Person movie north wrong thing group. Write exist church daughter up, why appear ahead growth, wife news protect. Save smile, impact improve direction trouble tax, scene, north nation, maybe hang face history. Cause lawyer true worker season, more.




Generador aleatorio de texto 'Lorem Ipsum'

( ESTA FUNCIÓN SIMPLEMENTA HACE UNA LLAMADA AL GENERADOR DE PÁRRAFOS QUE HE PUBLICADO ARRIBA. )

Código (vbnet) [Seleccionar]
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Generates a random 'Lorem Ipsum' paragraph.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>
''' Wikipedia article: <see href="https://en.wikipedia.org/wiki/Lorem_ipsum"/>
''' </remarks>
''' ----------------------------------------------------------------------------------------------------
''' <param name="numberOfParagraphs">
''' The number of paragraphs to generate.
''' </param>
'''
''' <param name="htmlFormatting">
''' Specifies whether or not to format paragraphs for HTML.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The resulting 'Lorem Ipsum' paragraph(s).
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Shared Function GenerateLoremIpsumText(ByVal numberOfParagraphs As Integer,
                                             ByVal htmlFormatting As Boolean) As String

   Dim words As String() = {
       "abhorreant", "accommodare", "accumsan", "accusam", "accusamus", "accusata", "ad",
       "adhuc", "adipisci", "adipiscing", "admodum", "adolescens", "adversarium", "aeque",
       "aeterno", "affert", "agam", "albucius", "alia", "alienum", "alii", "aliquam",
       "aliquando", "aliquid", "aliquip", "alterum", "amet", "an", "ancillae", "animal",
       "antiopam", "apeirian", "aperiam", "aperiri", "appareat", "appellantur", "appetere",
       "argumentum", "assentior", "assueverit", "assum", "at", "atomorum", "atqui", "audiam",
       "audire", "augue", "autem", "blandit", "bonorum", "brute", "case", "causae", "cetero",
       "ceteros", "choro", "cibo", "civibus", "clita", "commodo", "commune", "complectitur",
       "comprehensam", "conceptam", "concludaturque", "conclusionemque", "congue", "consectetuer",
       "consequat", "consequuntur", "consetetur", "constituam", "constituto", "consul", "consulatu",
       "contentiones", "convenire", "copiosae", "corpora", "corrumpit", "cotidieque", "cu", "cum",
       "debet", "debitis", "decore", "definiebas", "definitionem", "definitiones", "delectus",
       "delenit", "deleniti", "delicata", "delicatissimi", "democritum", "denique", "deseruisse",
       "deserunt", "deterruisset", "detracto", "detraxit", "diam", "dicam", "dicant", "dicat",
       "diceret", "dicit", "dico", "dicta", "dictas", "dicunt", "dignissim", "discere", "disputando",
       "disputationi", "dissentias", "dissentiet", "dissentiunt", "docendi", "doctus", "dolor",
       "dolore", "dolorem", "dolores", "dolorum", "doming", "duis", "duo", "ea", "eam", "efficiantur",
       "efficiendi", "ei", "eirmod", "eius", "elaboraret", "electram", "eleifend", "eligendi", "elit",
       "elitr", "eloquentiam", "enim", "eos", "epicurei", "epicuri", "equidem", "erant", "erat",
       "eripuit", "eros", "errem", "error", "erroribus", "eruditi", "esse", "essent", "est", "et",
       "etiam", "eu", "euismod", "eum", "euripidis", "everti", "evertitur", "ex", "exerci", "expetenda",
       "expetendis", "explicari", "fabellas", "fabulas", "facer", "facete", "facilis", "facilisi",
       "facilisis", "falli", "fastidii", "ferri", "feugait", "feugiat", "fierent", "forensibus",
       "fugit", "fuisset", "gloriatur", "graece", "graeci", "graecis", "graeco", "gubergren", "habemus",
       "habeo", "harum", "has", "hendrerit", "hinc", "his", "homero", "honestatis", "id", "idque",
       "ignota", "iisque", "illud", "illum", "impedit", "imperdiet", "impetus", "in", "inani", "inciderint",
       "incorrupte", "indoctum", "inermis", "inimicus", "insolens", "instructior", "integre", "intellegam",
       "intellegat", "intellegebat", "interesset", "interpretaris", "invenire", "invidunt", "ipsum",
       "iracundia", "iriure", "iudicabit", "iudico", "ius", "iusto", "iuvaret", "justo", "labitur",
       "laboramus", "labore", "labores", "laoreet", "latine", "laudem", "legendos", "legere", "legimus",
       "liber", "liberavisse", "libris", "lobortis", "lorem", "lucilius", "ludus", "luptatum", "magna",
       "maiestatis", "maiorum", "malis", "malorum", "maluisset", "mandamus", "mazim", "mea", "mediocrem",
       "mediocritatem", "mei", "meis", "mel", "meliore", "melius", "menandri", "mentitum", "minim",
       "minimum", "mnesarchum", "moderatius", "modo", "modus", "molestiae", "molestie", "mollis", "movet",
       "mucius", "mundi", "munere", "mutat", "nam", "natum", "ne", "nec", "necessitatibus", "neglegentur",
       "nemore", "nibh", "nihil", "nisl", "no", "nobis", "noluisse", "nominati", "nominavi", "nonumes",
       "nonumy", "noster", "nostro", "nostrud", "nostrum", "novum", "nulla", "nullam", "numquam", "nusquam",
       "oblique", "ocurreret", "odio", "offendit", "officiis", "omittam", "omittantur", "omnes", "omnesque",
       "omnis", "omnium", "oporteat", "oportere", "option", "oratio", "ornatus", "partem", "partiendo",
       "patrioque", "paulo", "per", "percipit", "percipitur", "perfecto", "pericula", "periculis", "perpetua",
       "persecuti", "persequeris", "persius", "pertinacia", "pertinax", "petentium", "phaedrum", "philosophia",
       "placerat", "platonem", "ponderum", "populo", "porro", "posidonium", "posse", "possim", "possit",
       "postea", "postulant", "praesent", "pri", "prima", "primis", "principes", "pro", "probatus", "probo",
       "prodesset", "prompta", "propriae", "purto", "putant", "putent", "quaeque", "quaerendum", "quaestio",
       "qualisque", "quando", "quas", "quem", "qui", "quidam", "quis", "quo", "quod", "quodsi", "quot",
       "rationibus", "rebum", "recteque", "recusabo", "referrentur", "reformidans", "regione", "reprehendunt",
       "reprimique", "repudiandae", "repudiare", "reque", "ridens", "sadipscing", "saepe", "sale", "salutandi",
       "salutatus", "sanctus", "saperet", "sapientem", "scaevola", "scribentur", "scripserit", "scripta",
       "scriptorem", "sea", "sed", "semper", "senserit", "sensibus", "sententiae", "signiferumque", "similique",
       "simul", "singulis", "sint", "sit", "soleat", "solet", "solum", "soluta", "sonet", "splendide", "stet",
       "suas", "suavitate", "summo", "sumo", "suscipiantur", "suscipit", "tacimates", "tale", "tamquam", "tantas",
       "tation", "te", "tempor", "temporibus", "theophrastus", "tibique", "timeam", "tincidunt", "tollit",
       "torquatos", "tota", "tractatos", "tritani", "ubique", "ullamcorper", "ullum", "unum", "urbanitas", "usu",
       "ut", "utamur", "utinam", "utroque", "vel", "velit", "veniam", "verear", "veri", "veritus", "vero",
       "verterem", "vide", "viderer", "vidisse", "vidit", "vim", "viris", "virtute", "vis", "vitae", "vituperata",
       "vituperatoribus", "vivendo", "vivendum", "vix", "vocent", "vocibus", "volumus", "voluptaria",
       "voluptatibus", "voluptatum", "voluptua", "volutpat", "vulputate", "wisi", "zril"}

   Dim str As String = RandomParagraphGenerator(words, numberOfParagraphs, htmlFormatting)

   If (htmlFormatting) Then
       Return str.Insert(3, "Lorem ipsum dolor sit amet. ")
   Else
       Return str.Insert(0, "Lorem ipsum dolor sit amet. ")
   End If

End Function


Modo de empleo:

Código (vbnet) [Seleccionar]
Dim loremIpsum As String = GenerateLoremIpsumText(numberOfParagraphs:=4, htmlFormatting:=True)
Console.WriteLine(loremIpsum)


Citar<p>Lorem ipsum dolor sit amet. Placerat vulputate tollit cum vivendo adipiscing nemore duo salutandi mollis. Fabellas malis, eros solet rationibus. Assum suas inermis, at veri prompta modo scaevola, ad. Percipitur ceteros semper vituperata feugait disputationi cotidieque soluta. Efficiendi facilisi zril percipit putant quando id quas nobis civibus natum. Pertinax maluisset vidisse oratio autem eripuit repudiandae ea suas eros illum oratio aliquid. Fabulas porro, integre oportere.</p>

<p>Virtute mediocritatem, vim erant nisl. Legendos postea saperet postea putent nihil facilisi nominati omnis. Facilisis persequeris scaevola alterum probatus vulputate denique pericula ullamcorper eloquentiam oporteat purto mediocritatem.</p>

<p>Veniam petentium delectus delicatissimi malis voluptua mentitum dissentias interpretaris verear quis utamur albucius verear. Quo reformidans, definitiones facilis. Conclusionemque quaestio voluptaria populo delicata sit viris mediocrem vulputate voluptatum eloquentiam. Quas an, bonorum cibo audiam commune volutpat. Vis ullamcorper scriptorem omnis facilisis sententiae hendrerit. Oporteat atomorum prompta suavitate idque accommodare ius oblique graece graecis interpretaris nemore. Meliore albucius commune qui suscipit definitiones vidit docendi facilisi forensibus quis. Equidem dolore expetendis iudico, delectus viderer timeam. Mediocrem molestie timeam, recteque, maluisset evertitur delicata.</p>

<p>Similique neglegentur temporibus alienum ad legimus scriptorem bonorum et appetere vide molestie. Mentitum feugait voluptatum illum detracto, tamquam vel ponderum mei illud, omnis paulo, ignota. Malorum lorem consul molestie interpretaris aperiri vituperatoribus, soluta enim vituperatoribus.</p>
#516
Cita de: Orubatosu en 19 Febrero 2019, 14:53 PM
O es una broma chorra de un troll, o el que hace la denuncia es un firme candidato a un hospital psiquiatrico

O peor que una broma, es una forma absurda para intentar sacarle dinero a sus padres...

No es el primero ni el último que hace demandas absurdas/ilógicas solo con fines económicos. Hay un individuo de EEUU creo que era, que tiene el record guinness de demandas, y este se cuenta en miles, y cada una es más absurda que la anterior... el tipo demanda a todo el mundo por cosas chorras y no se salvan ni los famosos xD.

saludos
#517
HardwareStress

( click en la imagen para descargar la librería o el código fuente )


HardwareStress es una biblioteca .NET que proporciona un mecanismo para estresar los recursos de hardware, como la CPU, disco o memoria RAM.

Como cualquier otro software enfocado para estresar  los recursos de hardware, usted debe usarlo bajo su propio riesgo. No me responsabilizo de un error de hardware.




Donaciones

Cualquier código dentro del espacio de nombres "DevCase" se distribuye libremente como parte del código fuente comercial de "DevCase for .NET Framework".

Tal vez te gustaría considerar comprar este conjunto de bibliotecas para apoyarme. Puede hacer un montón de cosas con mis bibliotecas para una gran cantidad de temáticas diversas, no solo relacionadas con hardware, etc.

Aquí hay un enlace a la página de compra:

Muchas gracias.




Uso

El uso es muy simple, hay 3 clases: CpuStress, DiskStress y MemoryStress que proporciona un método Allocate() para comenzar a estresar los recursos, y un método Deallocate() para detenerlo.




Ejemplos de uso

CPU Stress
Código (vbnet) [Seleccionar]
Using cpuStress As New CpuStress()
    Dim percentage As Single = 20.5F 20.50%

    Console.WriteLine("Allocating CPU usage percentage...")
    cpuStress.Allocate(percentage)
    Thread.Sleep(TimeSpan.FromSeconds(5))
    Console.WriteLine("Instance CPU average usage percentage: {0:F2}%", cpuStress.InstanceCpuPercentage)
    Console.WriteLine("Process  CPU average usage percentage: {0:F2}%", cpuStress.ProcessCpuPercentage)
    Console.WriteLine()

    Console.WriteLine("Deallocating CPU usage percentage...")
    cpuStress.Deallocate()
    Thread.Sleep(TimeSpan.FromSeconds(5))
    Console.WriteLine("Instance CPU average usage percentage: {0:F2}%", cpuStress.InstanceCpuPercentage)
    Console.WriteLine("Process  CPU average usage percentage: {0:F2}%", cpuStress.ProcessCpuPercentage)
End Using



Disk Stress
Código (vbnet) [Seleccionar]
Using diskStress As New DiskStress()
    Console.WriteLine("Allocating disk I/O read and write operations...")
    diskStress.Allocate(fileSize:=1048576) 1 MB

    Thread.Sleep(TimeSpan.FromSeconds(10))

    Console.WriteLine("Stopping disk I/O read and write operations...")
    diskStress.Deallocate()

    Console.WriteLine()
    Console.WriteLine("Instance disk I/O read operations count: {0} (total of files read)", diskStress.InstanceReadCount)
    Console.WriteLine("Process  disk I/O read operations count: {0}", diskStress.ProcessReadCount)
    Console.WriteLine()
    Console.WriteLine("Instance disk I/O read data (in bytes): {0} ({1:F2} GB)", diskStress.InstanceReadBytes, (diskStress.InstanceReadBytes / 1024.0F ^ 3))
    Console.WriteLine("Process  disk I/O read data (in bytes): {0} ({1:F2} GB)", diskStress.ProcessReadBytes, (diskStress.ProcessReadBytes / 1024.0F ^ 3))
    Console.WriteLine()
    Console.WriteLine("Instance disk I/O write operations count: {0} (total of files written)", diskStress.InstanceWriteCount)
    Console.WriteLine("Process  disk I/O write operations count: {0}", diskStress.ProcessWriteCount)
    Console.WriteLine()
    Console.WriteLine("Instance disk I/O written data (in bytes): {0} ({1:F2} GB)", diskStress.InstanceWriteBytes, (diskStress.InstanceWriteBytes / 1024.0F ^ 3))
    Console.WriteLine("Process  disk I/O written data (in bytes): {0} ({1:F2} GB)", diskStress.ProcessWriteBytes, (diskStress.ProcessWriteBytes / 1024.0F ^ 3))
End Using



Memory Stress
Código (vbnet) [Seleccionar]
Using memStress As New MemoryStress()
    Dim memorySize As Long = 1073741824 1 GB

    Console.WriteLine("Allocating physical memory size...")
    memStress.Allocate(memorySize)
    Console.WriteLine("Instance Physical Memory Size (in bytes): {0} ({1:F2} GB)", memStress.InstancePhysicalMemorySize, (memStress.InstancePhysicalMemorySize / 1024.0F ^ 3))
    Console.WriteLine("Process  Physical Memory Size (in bytes): {0} ({1:F2} GB)", memStress.ProcessPhysicalMemorySize, (memStress.ProcessPhysicalMemorySize / 1024.0F ^ 3))
    Console.WriteLine()
    Console.WriteLine("Deallocating physical memory size...")
    memStress.Deallocate()
    Console.WriteLine("Instance Physical Memory Size (in bytes): {0}", memStress.InstancePhysicalMemorySize)
    Console.WriteLine("Process  Physical Memory Size (in bytes): {0} ({1:F2} MB)", memStress.ProcessPhysicalMemorySize, (memStress.ProcessPhysicalMemorySize / 1024.0F ^ 2))
End Using

#518
HardwareStress

( click en la imagen para descargar la librería o el código fuente )


HardwareStress es una biblioteca .NET que proporciona un mecanismo para estresar los recursos de hardware, como la CPU, disco o memoria RAM.

Como cualquier otro software enfocado para estresar  los recursos de hardware, usted debe usarlo bajo su propio riesgo. No me responsabilizo de un error de hardware.




Donaciones

Cualquier código dentro del espacio de nombres "DevCase" se distribuye libremente como parte del código fuente comercial de "DevCase for .NET Framework".

Tal vez te gustaría considerar comprar este conjunto de bibliotecas para apoyarme. Puede hacer un montón de cosas con mis bibliotecas para una gran cantidad de temáticas diversas, no solo relacionadas con hardware, etc.

Aquí hay un enlace a la página de compra:

Muchas gracias.




Uso

El uso es muy simple, hay 3 clases: CpuStress, DiskStress y MemoryStress que proporciona un método Allocate() para comenzar a estresar los recursos, y un método Deallocate() para detenerlo.




Ejemplos de uso

CPU Stress
Código (vbnet) [Seleccionar]
Using cpuStress As New CpuStress()
    Dim percentage As Single = 20.5F 20.50%

    Console.WriteLine("Allocating CPU usage percentage...")
    cpuStress.Allocate(percentage)
    Thread.Sleep(TimeSpan.FromSeconds(5))
    Console.WriteLine("Instance CPU average usage percentage: {0:F2}%", cpuStress.InstanceCpuPercentage)
    Console.WriteLine("Process  CPU average usage percentage: {0:F2}%", cpuStress.ProcessCpuPercentage)
    Console.WriteLine()

    Console.WriteLine("Deallocating CPU usage percentage...")
    cpuStress.Deallocate()
    Thread.Sleep(TimeSpan.FromSeconds(5))
    Console.WriteLine("Instance CPU average usage percentage: {0:F2}%", cpuStress.InstanceCpuPercentage)
    Console.WriteLine("Process  CPU average usage percentage: {0:F2}%", cpuStress.ProcessCpuPercentage)
End Using



Disk Stress
Código (vbnet) [Seleccionar]
Using diskStress As New DiskStress()
    Console.WriteLine("Allocating disk I/O read and write operations...")
    diskStress.Allocate(fileSize:=1048576) 1 MB

    Thread.Sleep(TimeSpan.FromSeconds(10))

    Console.WriteLine("Stopping disk I/O read and write operations...")
    diskStress.Deallocate()

    Console.WriteLine()
    Console.WriteLine("Instance disk I/O read operations count: {0} (total of files read)", diskStress.InstanceReadCount)
    Console.WriteLine("Process  disk I/O read operations count: {0}", diskStress.ProcessReadCount)
    Console.WriteLine()
    Console.WriteLine("Instance disk I/O read data (in bytes): {0} ({1:F2} GB)", diskStress.InstanceReadBytes, (diskStress.InstanceReadBytes / 1024.0F ^ 3))
    Console.WriteLine("Process  disk I/O read data (in bytes): {0} ({1:F2} GB)", diskStress.ProcessReadBytes, (diskStress.ProcessReadBytes / 1024.0F ^ 3))
    Console.WriteLine()
    Console.WriteLine("Instance disk I/O write operations count: {0} (total of files written)", diskStress.InstanceWriteCount)
    Console.WriteLine("Process  disk I/O write operations count: {0}", diskStress.ProcessWriteCount)
    Console.WriteLine()
    Console.WriteLine("Instance disk I/O written data (in bytes): {0} ({1:F2} GB)", diskStress.InstanceWriteBytes, (diskStress.InstanceWriteBytes / 1024.0F ^ 3))
    Console.WriteLine("Process  disk I/O written data (in bytes): {0} ({1:F2} GB)", diskStress.ProcessWriteBytes, (diskStress.ProcessWriteBytes / 1024.0F ^ 3))
End Using



Memory Stress
Código (vbnet) [Seleccionar]
Using memStress As New MemoryStress()
    Dim memorySize As Long = 1073741824 1 GB

    Console.WriteLine("Allocating physical memory size...")
    memStress.Allocate(memorySize)
    Console.WriteLine("Instance Physical Memory Size (in bytes): {0} ({1:F2} GB)", memStress.InstancePhysicalMemorySize, (memStress.InstancePhysicalMemorySize / 1024.0F ^ 3))
    Console.WriteLine("Process  Physical Memory Size (in bytes): {0} ({1:F2} GB)", memStress.ProcessPhysicalMemorySize, (memStress.ProcessPhysicalMemorySize / 1024.0F ^ 3))
    Console.WriteLine()
    Console.WriteLine("Deallocating physical memory size...")
    memStress.Deallocate()
    Console.WriteLine("Instance Physical Memory Size (in bytes): {0}", memStress.InstancePhysicalMemorySize)
    Console.WriteLine("Process  Physical Memory Size (in bytes): {0} ({1:F2} MB)", memStress.ProcessPhysicalMemorySize, (memStress.ProcessPhysicalMemorySize / 1024.0F ^ 2))
End Using

#519
Hijos de put@ desagradecidos de la vida los hay en todas partes, sobre todo ricachones que lo tienen todo y se quejan por pequeñeces sin importancia comparado con gente pobre que tiene que mendigar para llevarse algo a la boca y sobrevivir un día más, o comparado con enfermos terminales o con gente que vive al límite de ser asesinado cada día (ej. en Venezuela), pero lo del Samuel este es el extremo más repugnante e inverosimil... cuesta creer que exista alguien tan desagradecido con la vida. Y digo yo, ¿por que no se suicida y ya está?.

Me saca de mis casillas. Y la noticia ni la puedo leer entera, ¿para qué?, no merece la pena despues de haber leido el titular.

El mundo se va a la mierd...

Un saludo.
#520
Cita de: Machacador en 17 Febrero 2019, 22:29 PM
Pobre Elektro... la gringofobia y perrofobia lo tienen loco... nada mas le queda refugiarse en el amor de un gato, solo que los gatos son de lo mas indiferentes... jejejejejeeee...

:rolleyes: :o :rolleyes:

No es que quiera amenazarte ni nada, pero el otro día le enseñé un truco a mi gata...



...y ya no tiene con quien seguir practicando. :rolleyes:

Por cierto, la "gringofobia" es lo más sano que hay; el rechazo hacia Trump, los rednecks, los amish, las comunidades barriobajeras de gente negra, o estados que están llenos de laboratorios caseros donde se fabrican todo tipo de sustancias estupefacientes y eso pone tu vida en peligro (ej. Texas), además de las ciudades llenas de ridículos hipsters u otras culturas urbanas pseudo-intelectuales, y sobre todo lo demás el rechazo hacia la policía yankee... todo eso te puede evitar una muerte prematura por ser confiado con esa gente. El único lugar seguro de EEUU para vivir: cualquier sitio donde no haya un McDonalds en 30 kilómetros, ni una tienda de armas ni tampoco policía. ¿Existe ese lugar?, si... "solamente es necesario" alejarse con un barco con las suficientes provisiones para sobrevivir en el mar...