Simulando barra de progreso

Iniciado por Meta, 27 Febrero 2019, 22:29 PM

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

Meta

Hola:

Independientemente de la cantidad de █ haya para crear una barra de progreso, no llega al 100 %.


Este es su código que he hecho hasta ahora.
using System;
using System.Threading;

namespace Porcentaje_barra_consola_01_cs
{
   class Program
   {
       public static int resultado = 0;

       static void Main(string[] args)
       {
           // Título de la ventana.
           Console.Title = "Simulaor barra";

           // Tamaño ventana consola.
           Console.WindowWidth = 60; // X ancho.
           Console.WindowHeight = 20; // Y altura.

           // Cursor invisible.
           Console.CursorVisible = false;

           // Variables.
           int barra = 49;
           int porcentaje = 0;

           Console.SetCursorPosition(17, 1);
           Console.Write("    ");
           Console.SetCursorPosition(17, 1);
           Console.Write("");

           // Dibujamos la barra del portentaje.
           Console.SetCursorPosition(0, 3);
           Console.Write("0 %                         50 %                       100 %");
           Console.SetCursorPosition(0, 4);
           Console.Write("┌────────────────────────────┬───────────────────────────┐");
           Console.SetCursorPosition(0, 5);
           Console.ForegroundColor = ConsoleColor.Yellow;

           // Barra de progreso.
           for (int i = 0; i <= barra; i++)
           {
               Console.Write("█"); // Muestra ASCII 219 Dec y DB en Hex.
                                   // Console.Write((char)219);
                                   // Console.Write(Encoding.ASCII.GetBytes((char)219));
               porcentaje++; // Incrementa valor.

               printCargando(porcentaje);

               Thread.Sleep(100); // 100 ms o 0.1 segundos.
           }

           Console.ReadKey();
       }

       static void printCargando(int porcentaje)
       {
           Console.ForegroundColor = ConsoleColor.Gray;
           Console.SetCursorPosition(0, 1);
           // Por dos para que simule el 100%.
           Console.Write("Cargado: " + (porcentaje).ToString() + " %");
           //Console.Write("Cargado: {0} %", (porcentaje * 2).ToString());
           //Console.Write($"Cargado: { (porcentaje * 2).ToString() } %");

           // Reestablecemos para que vuelva a imprimir bajo la línea de carga.
           Console.ForegroundColor = ConsoleColor.Yellow;
           Console.SetCursorPosition(porcentaje, 5);
       }

   }
}


Gracias. ;)
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/

Eleкtro

#1
Cita de: Meta en 27 Febrero 2019, 22:29 PM
Independientemente de la cantidad de █ haya para crear una barra de progreso, no llega al 100 %.

Citar
Código (csharp) [Seleccionar]
int barra = 49;
Citar
Código (csharp) [Seleccionar]
for (int i = 0; i <= barra; i++) { ... }

La longitud de caracteres de esa "barra de progreso" son 58, no 49...

Citar
Código (csharp) [Seleccionar]
porcentaje++; // Incrementa valor.

En ninguna parte del código estás calculando un porcentaje, tan solo incrementas un valor. Logicamente tal y como tienes ahora mismo ese código, la única manera de que ese "porcentaje" llegue a 100 sería incrementar el valor 100 veces.

Supongo que no necesitarás que te explique la fórmula para calcular un porcentaje...

Código (csharp) [Seleccionar]
int barra = 58;
double porcentaje = 0;

for (int i = 0; i < barra; i++) {
porcentaje = ((i + 1.0D) / (barra / 100.0));
}


Y el método ese "printCargando" sencillamente está mal planteado al tomar un valor de porcentaje como parámetro y usarlo tal cual en el método Console.SetCursorPosition()... no tiene sentido.

Saludos.








Serapis

La forma más coherente (a cambio de posiblemente, algunas líneas más de código), es encapuslar lo mínimo de una barras de progreso (que uses una clase o lo dejes ahí suelto, ya es cosa tuya):
Campos:
- Mínimo
- Maximo
- Valor
Metodos:
- Inicializar(min, cantidad, valor, [fila, columna])
- Incrementar(+x) //con alguna sobrecarga
- Dibujar(dibcosasprevias)   // Actualizar el 'gráfico'.


Y tratándose de consola, convendría además mantener la fila donde dibujar y la columna inicial de dibujado, ambos valores pueden ser pasados al inicializar...

NOTA: que no se acomete comprobaciones, si lo vas a usar tú es obvio que no pondrás valor fuera de límites.
funcion Inicializar(0,100,0, fila=5, columna=12)
   p_Min = min
   p_Max = p_min + (Cantidad-1)  //nótese que cantidad puede ser negativo, y consecuentemente max serlo también, si no se desea designar tipos sin signo).
   p_Valor = valor
   p_Fila = Fila
   p_Columna = columna
   Dibujar(true)
fin funcion

propiedad Set Valor(x)  // propiedad Get Valor ... probablemente solo precises que sea de escritura.
    Si (x <> p_Valor)
       p_valor = x
       dibujar(false)
    fin si
fin propiedad

funcion Incrementar(x)
    p_valor +=x
    dibujar(false)
fin funcion
funcion Incrementar
    Incrementar(1)
fin funcion

funcion Dibujar(previo)
    si previo
        dibujar infoprevia //texto, etc... se supone que basado en p_fila -algo
    fin si

    establecer posicioncursor(p_fila, p_columna)
    bucle desde p_min a p_valor
        dibujar char(219) 
    siguiente
fin funcion


Luego simplemente inicializas con los valores oportunos... y ya se dibuja.
Cuando hagas alguna tarea de carga usarías valor = x o incrementar o incrementar(x) como remplazo de tu 'printCargando'. Usar uno u otro depende de lo que se haga, en el bucle posiblemente 'incrementar' vaya bien, pero si hay algna tarea anterior o posterior pudiera darse un incremntar(10) (por ejemplo), o si hay varias tareas, volver a ponerlo a 0 Valor = 0, incluso un nuevo Inicializar(,,,) si los límites son diferentes...

La gran ventaja de hacerlo más estructurado (que solo líneas espagueti sin fin) es que con posterioridad cualquier cambio, es más sencillo de llevar a cabo y si pasa demasiado tiempo, un simple vistazo sobra para entender lo que hacía y saber donde tocar si se quiere hacer algún cambio, sin perder tiempo en empaparse con lo escrito tiempo/años atrás. Por ejemplo, alojado en una clase, podrías reutilizarlo en distintos proyectos, con tan solo cambiar lo que se dibuje como 'info previa', (los textos que se asocien a lo que se haga, como 'leyendo fichero...', 'buscando...', ordenando...', etc... que si además lo parametrizas, pués mejor que mejor).

Eleкtro

#3
Si es que...

Aquí publicaste un tema relacionado en el año 2016:

Y aquí otro en el 2017:

...

A ver, yo soy el primero en reconocer que soy malísimo con las matemáticas, pero si te han estado explicando como calcular un porcentaje durante años y todavía sigues preguntando lo mismo y no te da para repasar las respuestas que te ofrecieron a esos temas que creaste en el foro, pues yo ya no se que nombre tiene eso...

Muchas veces pienso que estas dudas son un trolleo y que es una pérdida de tiempo escribir respuestas largas en tus temas precisamente por eso... y por que el tiempo y los años demuestra que no lees lo que te dicen, por que sigues preguntando exactamente lo mismo que hace 3 años (en este y otros temas distintos, siempre ocurre lo mismo contigo).













Vamos a ver... hace unos años desarrollé esta barra de progreso reutilizable para aplicaciones de consola...



partiendo de esta idea en C# que tomé como base e inspiración:

El código (el cual no está muy optimizado, todo hay que decirlo) lo puedes pegar en un nuevo proyecto de VB.NET para generar un archivo dll, o lo puedes convertir a C# si prefieres. O también puedes usar el código original en C#, aunque no es tan personalizable como este de aquí abajo.

Si despues de esto sigues teniendo dudas y necesitas ayuda con la utilización de barras de progreso y cálculo de porcentajes, yo me daré por vencido para siempre...

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 12-December-2016
' ***********************************************************************

#Region " Imports "

Imports System.Drawing
Imports System.Text
Imports System.Threading

' Imports DevCase.Core.Application.UserInterface.Tools.Console
' Imports DevCase.Core.Design

#End Region

#Region " Console ProgressBar "

'Namespace DevCase.Core.Application.UserInterface

'#If Not NET40 Then

''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' A personalizable colorful ASCII progress bar for console applications.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>
''' Based on: <see href="https://gist.github.com/DanielSWolf/0ab6a96899cc5377bf54"/>
''' </remarks>
''' ----------------------------------------------------------------------------------------------------
''' <example> This is a code example.
''' <code>
''' Public Module Module1
'''
'''     Public Sub Main()
'''         Console.CursorVisible = False
'''         Console.Write("Performing some task... ")
'''
'''         Using progress As New ConsoleProgressBar(blockCount:=20) With {
'''             .Animation = "||//--\\".ToCharArray(),
'''             .AnimationSpeed = TimeSpan.FromMilliseconds(125),
'''             .AnimationBackColor = Console.BackgroundColor,
'''             .AnimationForeColor = ConsoleColor.Yellow,
'''             .BlockActiveChar = "█"c,
'''             .BlockInactiveChar = "·"c,
'''             .BlockActiveBackColor = Console.BackgroundColor,
'''             .BlockActiveForeColor = ConsoleColor.Green,
'''             .BlockInactiveBackColor = Console.BackgroundColor,
'''             .BlockInactiveForeColor = ConsoleColor.DarkGray,
'''             .BorderBackColor = Console.BackgroundColor,
'''             .BorderForeColor = ConsoleColor.White,
'''             .ProgressTextFormat = "{1} of {2} ({0}%)",
'''             .ProgressTextBackColor = Console.BackgroundColor,
'''             .ProgressTextForeColor = ConsoleColor.Gray
'''         }
'''
'''             For i As Integer = 0 To 100
'''                 progress.Report(i / 100)
'''                 Thread.Sleep(100)
'''             Next i
'''         End Using
'''
'''         Console.WriteLine()
'''         Console.WriteLine("Done.")
'''         Console.ReadKey()
'''     End Sub
'''
''' End Module
''' </code>
''' </example>
''' ----------------------------------------------------------------------------------------------------
Public NotInheritable Class ConsoleProgressBar : Implements IDisposable : Implements IProgress(Of Double)

#Region " Properties "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the current progress value. From 0.0 to 1.0
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The current progress value. From 0.0 to 1.0
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public ReadOnly Property CurrentProgress As Double
           Get
               Return Me.currentProgressB
           End Get
       End Property
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The current progress value. From 0.0 to 1.0
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private currentProgressB As Double

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the amount of blocks to display in the progress bar.
       ''' <para></para>
       ''' Default value is: 20
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The amount of blocks to display in the progress bar.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public ReadOnly Property BlockCount As Integer

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the character used to draw an active progress bar block.
       ''' <para></para>
       ''' Default value is: "#"
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The character used to draw an active progress bar block.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property BlockActiveChar As Char

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets the character used to draw an inactive progress bar block.
       ''' <para></para>
       ''' Default value is: "·"
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The character used to draw an inactive progress bar block.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property BlockInactiveChar As Char

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the background of an active progress bar block.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="ConsoleColor"/> used to paint the background of an active progress bar block.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property BlockActiveBackColor As ConsoleColor

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the foreground of an active progress bar block.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="ConsoleColor"/> used to paint the foreground of an active progress bar block.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property BlockActiveForeColor As ConsoleColor

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the background of a inactive progress bar block.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="ConsoleColor"/> used to paint the background of a inactive progress bar block.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property BlockInactiveBackColor As ConsoleColor

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the foreground of a inactive progress bar block.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="ConsoleColor"/> used to paint the foreground of a inactive progress bar block.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property BlockInactiveForeColor As ConsoleColor

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the background of the borders of the progress bar.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="ConsoleColor"/> used to paint the background of the borders of the progress bar.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property BorderBackColor As ConsoleColor

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the foreground of the borders of the progress bar.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="ConsoleColor"/> used to paint the foreground of the borders of the progress bar.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property BorderForeColor As ConsoleColor

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the format of the progress text, where:
       ''' <para></para> {0} = Percentage Value
       ''' <para></para> {1} = Current Value
       ''' <para></para> {2} = Maximum Value
       ''' <para></para>
       ''' Default value is: "{0}%"
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The format of the percentage string.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property ProgressTextFormat As String

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the background of the progress text.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="ConsoleColor"/> used to paint the background of the borders of the progress text.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property ProgressTextBackColor As ConsoleColor

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the foreground of the borders of the progress text.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="ConsoleColor"/> used to paint the foreground of the borders of the progress text.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property ProgressTextForeColor As ConsoleColor

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the characters used to draw the animation secuence at the very end of the progress bar.
       ''' <para></para>
       ''' Default value is: {"|"c, "|"c, "/"c, "/"c, "-"c, "-"c, "\"c, "\"c}  ( that is: "||//--\\" )
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The characters used to draw the animation secuence at the very end of the progress bar.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property Animation As Char()

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the speed (framerate) of the animation secuence defined in <see cref="ConsoleProgressBar.Animation"/>.
       ''' <para></para>
       ''' Default value is: 125 milliseconds.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The speed (framerate) of the animation secuence defined in <see cref="ConsoleProgressBar.Animation"/>.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property AnimationSpeed As TimeSpan

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the background of the animation secuence.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="ConsoleColor"/> used to paint the background of the borders of the animation secuence.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property AnimationBackColor As ConsoleColor

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the foreground of the borders of the animation secuence.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' The <see cref="ConsoleColor"/> used to paint the foreground of the borders of the animation secuence.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property AnimationForeColor As ConsoleColor

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets or sets a value indicating whether the animation secuence is visible in the progress bar.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <value>
       ''' A value indicating whether the animation secuence is visible in the progress bar.
       ''' </value>
       ''' ----------------------------------------------------------------------------------------------------
       Public Property AnimationVisible As Boolean

#End Region

#Region " Private Fields "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The timer.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private ReadOnly timer As Threading.Timer

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The current animation index.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private animationIndex As Integer

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The cursor position in the console buffer when instancing the <see cref="ConsoleProgressBar"/> class.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private cursorPos As Point

#End Region

#Region " Constructors "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Prevents a default instance of the <see cref="ConsoleProgressBar"/> class from being created.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private Sub New()
       End Sub

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Initializes a new instance of the <see cref="ConsoleProgressBar"/> class.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="blockCount">
       ''' The amount of blocks to display in the progress bar. Default value is: 20
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Sub New(Optional ByVal blockCount As Integer = 10)

           If (blockCount < 2) Then
               Throw New ArgumentException(message:="Block count must be a value greater than 1.", paramName:=NameOf(blockCount))
           End If

           Me.BlockCount = blockCount
           Me.BlockActiveChar = "#"c
           Me.BlockInactiveChar = "·"c

           Me.BlockActiveBackColor = Console.BackgroundColor
           Me.BlockActiveForeColor = Console.ForegroundColor
           Me.BlockInactiveBackColor = Console.BackgroundColor
           Me.BlockInactiveForeColor = Console.ForegroundColor
           Me.BorderBackColor = Console.BackgroundColor
           Me.BorderForeColor = Console.ForegroundColor

           Me.Animation = "||//--\\".ToCharArray()
           Me.AnimationSpeed = TimeSpan.FromMilliseconds(100)
           Me.AnimationVisible = True
           Me.AnimationBackColor = Console.BackgroundColor
           Me.AnimationForeColor = Console.ForegroundColor

           Me.ProgressTextFormat = "{0}%"
           Me.ProgressTextBackColor = Console.BackgroundColor
           Me.ProgressTextForeColor = Console.ForegroundColor

           Me.timer = New Timer(AddressOf Me.TimerCallback)

           Me.cursorPos = New Point(Console.CursorLeft, Console.CursorTop)

           ' A progress bar is only for temporary display in a console window.
           ' If the console output is redirected to a text file, draw nothing.
           ' Otherwise, we will end up with a lot of garbage in the target text file.
           If Not Console.IsOutputRedirected Then
               Me.ResetTimer()
           End If

       End Sub

#End Region

#Region " Public Methods "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Reports a progress update.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="value">
       ''' The value of the updated progress.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Public Sub Report(ByVal value As Double) Implements IProgress(Of Double).Report
           ' Make sure value is in [0..1] range
           value = Math.Max(0, Math.Min(1, value))
           Interlocked.Exchange(Me.currentProgressB, value)
       End Sub

#End Region

#Region " Private Methods "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Handles the calls from <see cref="ConsoleProgressBar.timer"/>.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="state">
       ''' An object containing application-specific information relevant to the
       ''' method invoked by this delegate, or <see langword="Nothing"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       Private Sub TimerCallback(ByVal state As Object)

           SyncLock Me.timer
               If (Me.isDisposed) Then
                   Exit Sub
               End If

               Me.UpdateText()
               Me.ResetTimer()
           End SyncLock

       End Sub

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Resets the timer.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private Sub ResetTimer()
           Me.timer.Change(Me.AnimationSpeed, TimeSpan.FromMilliseconds(-1))
       End Sub

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Updates the progress bar text.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private Sub UpdateText()

           Dim currentBlockCount As Integer = CInt(Me.currentProgressB * Me.BlockCount)
           Dim percent As Integer = CInt(Me.currentProgressB * 100)

           Dim text As String =
                   String.Format("[{0}{1}] {2} {3}",
                                 New String(Me.BlockActiveChar, currentBlockCount),
                                 New String(Me.BlockInactiveChar, Me.BlockCount - currentBlockCount),
                                 String.Format(Me.ProgressTextFormat, percent, (Me.currentProgressB * 100), 100),
                                 Me.Animation(Math.Max(Interlocked.Increment(Me.animationIndex), Me.animationIndex - 1) Mod Me.Animation.Length))
           Dim textLen As Integer = text.Length

           Dim coloredText As New StringBuilder()
           With coloredText
               .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.BorderBackColor), CInt(Me.BorderForeColor),
                                 "[")

               .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.BlockActiveBackColor), CInt(Me.BlockActiveForeColor),
                                 New String(Me.BlockActiveChar, currentBlockCount))

               .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.BlockInactiveBackColor), CInt(Me.BlockInactiveForeColor),
                                 New String(Me.BlockInactiveChar, Me.BlockCount - currentBlockCount))

               .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.BorderBackColor), CInt(Me.BorderForeColor),
                                 "]")
               .Append(" ")
               .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.ProgressTextBackColor), CInt(Me.ProgressTextForeColor),
                                 String.Format(Me.ProgressTextFormat, percent, (Me.currentProgressB * 100), 100))

               .Append(" ")
               If Me.AnimationVisible Then
                   .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.AnimationBackColor), CInt(Me.AnimationForeColor),
                                     Me.Animation(Math.Max(Interlocked.Increment(Me.animationIndex), Me.animationIndex - 1) Mod Me.Animation.Length))
               End If
           End With

           ' Lazy error handling when the console window is resized by the end-user.
           Try
               If (Console.BufferWidth > textLen) Then
                   coloredText.Append(" "c, Console.BufferWidth - text.Length)
               End If
               Console.SetCursorPosition(Me.cursorPos.X, Me.cursorPos.Y)
               ConsoleUtil.WriteColorText(coloredText.ToString(), {"*"c})

           Catch ex As Exception
               ' Do nothing.
           End Try

       End Sub

#End Region

#Region " IDisposable Implementation "

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Flag to detect redundant calls when disposing.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Private isDisposed As Boolean = False

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Releases all the resources used by this instance.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Public Sub Dispose() Implements IDisposable.Dispose
           Me.Dispose(isDisposing:=True)
       End Sub

       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
       ''' Releases unmanaged and, optionally, managed resources.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="isDisposing">
       ''' <see langword="True"/>  to release both managed and unmanaged resources;
       ''' <see langword="False"/> to release only unmanaged resources.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Protected Sub Dispose(ByVal isDisposing As Boolean)

           If (Not Me.isDisposed) AndAlso (isDisposing) Then
               SyncLock Me.timer
                   Me.UpdateText()
               End SyncLock
               If (Me.timer IsNot Nothing) Then
                   Me.timer.Dispose()
               End If
           End If

           Me.isDisposed = True

       End Sub

#End Region

   End Class

'#End If

'End Namespace

#End Region

'Namespace DevCase.Core.Application.UserInterface.Tools.Console

Public NotInheritable Class ConsoleUtil

#Region " Public Methods "

   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Writes colored text to the console.
   ''' <para></para>
   ''' Use <c>*F##*</c> as the start delimiter of the ForeColor, use <c>*-F*</c> as the end delimiter of the ForeColor.
   ''' <para></para>
   ''' Use <c>*B##*</c> as the start delimiter of the BackColor, use <c>*-B*</c> as the end delimiter of the BackColor.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <example> This is a code example.
   ''' <code>
   ''' WriteColorText("*F10*Hello *F14*World!*-F*", {"*"c})
   ''' </code>
   ''' </example>
   ''' ----------------------------------------------------------------------------------------------------
   ''' <param name="text">
   ''' The color-delimited text to write.
   ''' </param>
   '''
   ''' <param name="delimiters">
   ''' A set of 1 or 2 delimiters to parse the color-delimited string.
   ''' </param>
   ''' ----------------------------------------------------------------------------------------------------
   <DebuggerStepThrough>
   Public Shared Sub WriteColorText(ByVal text As String,
                                        ByVal delimiters As Char())

       ' Save the current console colors to later restore them.
       Dim oldForedColor As ConsoleColor = Console.ForegroundColor
       Dim oldBackColor As ConsoleColor = Console.BackgroundColor

       ' Split the string to retrieve and parse the color-delimited strings.
       Dim stringParts As String() =
                   text.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)

       ' Parse the string parts.
       For Each part As String In stringParts

           If (part.ToUpper Like "F#") OrElse (part.ToUpper Like "F##") Then
               ' Use the new ForeColor.
               Console.ForegroundColor = DirectCast(CInt(part.Substring(1)), ConsoleColor)

           ElseIf (part.ToUpper Like "B#") OrElse (part.ToUpper Like "B##") Then
               ' Use the new BackgroundColor.
               Console.BackgroundColor = DirectCast(CInt(part.Substring(1)), ConsoleColor)

           ElseIf (part.ToUpper Like "-F") Then
               ' Use the saved Forecolor.
               Console.ForegroundColor = oldForedColor

           ElseIf (part.ToUpper Like "-B") Then
               ' Use the saved BackgroundColor.
               Console.BackgroundColor = oldBackColor

           Else ' String part is not a delimiter so we can print it.
               Console.Write(part)

           End If

       Next part

       ' Restore the saved console colors.
       Console.ForegroundColor = oldForedColor
       Console.BackgroundColor = oldBackColor

   End Sub

#End Region

   Private Sub New()
   End Sub

End Class

'End Namespace


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

   Public Sub Main()
       Console.CursorVisible = False
       Console.Write("Performing some task... ")

       Using progress As New ConsoleProgressBar(blockCount:=20) With {
           .Animation = "||//--\\".ToCharArray(),
           .AnimationSpeed = TimeSpan.FromMilliseconds(125),
           .AnimationBackColor = Console.BackgroundColor,
           .AnimationForeColor = ConsoleColor.Yellow,
           .BlockActiveChar = "█"c,
           .BlockInactiveChar = "·"c,
           .BlockActiveBackColor = Console.BackgroundColor,
           .BlockActiveForeColor = ConsoleColor.Green,
           .BlockInactiveBackColor = Console.BackgroundColor,
           .BlockInactiveForeColor = ConsoleColor.DarkGray,
           .BorderBackColor = Console.BackgroundColor,
           .BorderForeColor = ConsoleColor.White,
           .ProgressTextFormat = "{1} of {2} ({0}%)",
           .ProgressTextBackColor = Console.BackgroundColor,
           .ProgressTextForeColor = ConsoleColor.Gray
       }

           For i As Integer = 0 To 100
               progress.Report(i / 100)
               Thread.Sleep(100)
           Next i
       End Using

       Console.WriteLine()
       Console.WriteLine("Done.")
       Console.ReadKey()
   End Sub

End Module


Por cierto, ese código lo comparto de manera libre aunque lo cierto es que forma parte del código fuente del framework comercial DevCase for .NET Framework para desarrolladores .NET.

Saludos...








Meta

#4
Buenas gente.

He hecho esto gracia a ustedes y no me dibuja la línea.

Código (csharp) [Seleccionar]
using System;
using System.Threading;

namespace Barra_progreso_consola_01_cs
{
    class Program
    {
        static void Main(string[] args)
        {
            // Título de la ventana.
            Console.Title = "Simulaor barra";

            // Tamaño ventana consola.
            Console.WindowWidth = 60; // X ancho.
            Console.WindowHeight = 20; // Y altura.

            // Cursor invisible.
            Console.CursorVisible = false;

            // Variables.
            int barra = 58;
            double porcentaje = 0;

            Console.SetCursorPosition(17, 1);
            Console.Write("    ");
            Console.SetCursorPosition(17, 1);
            Console.Write("");

            // Dibujamos la barra del portentaje.
            Console.SetCursorPosition(0, 3);
            Console.Write("0 %                         50 %                       100 %");
            Console.SetCursorPosition(0, 4);
            Console.Write("┌────────────────────────────┬───────────────────────────┐");
            //Console.SetCursorPosition(0, 5);
            //Console.ForegroundColor = ConsoleColor.Yellow;

            // Barra de progreso.
            for (int i = 0; i <= barra; i++)
            {
                porcentaje = ((i + 1.0D) / (barra / 100.0));
                Console.Write("█"); // Muestra ASCII 219 Dec y DB en Hex.
                                    // Console.Write((char)219);
                                    // Console.Write(Encoding.ASCII.GetBytes((char)219));
                porcentaje++; // Incrementa valor.

                printCargando(porcentaje);

                Thread.Sleep(20); // 100 ms o 0.1 segundos.
            }

            Console.ReadKey();
        }

        static void printCargando(double porcentaje)
        {
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.SetCursorPosition(0, 1);
            // Por dos para que simule el 100%.
            Console.Write("Cargado: " + (porcentaje).ToString("N2") + " %");
            //Console.Write("Cargado: {0} %", (porcentaje).ToString("N2"));
            //Console.Write($"Cargado: { (porcentaje).ToString() } %");

            // Reestablecemos para que vuelva a imprimir bajo la línea de carga.
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.SetCursorPosition(0, 5);
        }
    }
}


Esto si que es una buena barra de progreso.


Buen trabajo, lo haré cuando pueda.
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/

Serapis

#5
Cita de: Meta en 28 Febrero 2019, 18:02 PM
...He hecho esto gracia a ustedes y no me dibuja la línea...
mmm.... Me hace gracia eso...
Gracias a ¿nosotros?. Más bien gracias a tí...

Ya sé que no vas a adoptar la solución que te propone Elektro, porque son muchas líneas de código... pero la que yo te propuse no son muchas más que las que tu ya tienes... Y es que en realidad lleva solo 5 minutos, pasar mi pseudocódigo a código:

Eso sí, en Visual Basic, en C# y lenguajes similares, me aburre la cansina sintaxis de tanto punto y coma, de tanta llave y paréntesis, y la estúpida insistencia en ser sensible a la capitalización... I'm sorry, pero pasarlo a c# es casi casi idéntico...
Código (vbnet) [Seleccionar]

Imports System.Threading

Module Module1
   Sub Main()
       Console.Title = "Simulador barra de progreso"
       Console.WindowWidth = 80   ' X ancho.
       Console.WindowHeight = 20  ' Y altura.
       Console.CursorVisible = False  

       Dim k As UInteger
       Dim p As Progreso = New Progreso(0, 58, 0, 5) ' por defecto columna 12
       For k = 0 To p.Maximo
           p.Incrementar()     ' incrementa y redibuja todo.
           Thread.Sleep(40)    ' 40 milisegundos.
       Next

       Console.ReadKey()
   End Sub

   Private Class Progreso
       Dim p_Min, p_Max As UInteger
       Dim p_Fila, p_Columna As UInteger
       Dim p_Valor, s_Avance, s_Porcen As Single
       Dim FullProgreso As String

       Sub New(ByVal Min As UInteger, ByVal Cantidad As UInteger, ByVal Value As UInteger, Optional ByVal Fila As UInteger = 5, Optional ByVal Columna As UInteger = 12)
           p_Min = Min
           p_Max = (p_Min + Cantidad - 1)
           p_Valor = Value
           s_Avance = (Cantidad / 100)
           s_Porcen = (100 / Cantidad)
           FullProgreso = Strings.StrDup(Integer.Parse(Cantidad), Chr(177)) ' 219

           p_Fila = Fila
           p_Columna = Columna

           Me.Dibujar(True)
       End Sub

       Public ReadOnly Property Maximo As UInteger
           Get
               Return p_Max
           End Get
       End Property

       Public Sub Incrementar()
           p_Valor += s_Avance
           Me.Dibujar(False)
       End Sub

       Private Sub Dibujar(ByVal Previo As Boolean)
           Console.ForegroundColor = ConsoleColor.Red
           If (Previo = True) Then          ' Dibujamos la barra del portentaje.              
               Console.SetCursorPosition(p_Columna, p_Fila - 2)
               Console.Write("0 %                         50 %                     100 %")
               Console.SetCursorPosition(p_Columna - 1, p_Fila - 1)
               Console.Write("{0}{1}{0}", Chr(179), Strings.StrDup(Convert.ToInt32(p_Max - p_Min + 1), Chr(205))) ' 205= 2 rayas horizontales 240=1raya horizontal. 179=carácter de puntos (no macizo)
           End If
           Console.SetCursorPosition(p_Columna, p_Fila - 4)
           Console.Write("Cargado: {0} {1}", (p_Valor * s_Porcen / s_Avance).ToString("N2"), " %")
           Console.ForegroundColor = ConsoleColor.Yellow
           Console.SetCursorPosition(p_Columna, p_Fila)
           Console.Write(FullProgreso.Substring(0, (p_Valor / s_Avance)))
       End Sub

       ' No se usa en este ejemplo
       'Public WriteOnly Property Valor() As UInteger
       '    Set(ByVal value As UInteger)
       '        p_Valor = value
       '        Me.Dibujar(False)
       '    End Set
       'End Property
   End Class
End Module


P.d: Y aquí el aspecto de como se ve...


Meta

#6
Buenas:

Intenté pasarlo con este enlace, pero me daba errores por todoas partes.

Al final ya me sale.



Código (csharp) [Seleccionar]
using System;
using System.Threading;

namespace Barra_progreso_consola_03_cs
{
    class Program
    {
        // Variable.
        static double resultadoPorcentaje;

        static void Main(string[] args)
        {
            Console.Title = "Simulador barra de progreso";
            Console.WindowWidth = 60;   // X ancho.
            Console.WindowHeight = 10;  // Y altura.
            Console.CursorVisible = false;

            // Variable.
            int barra = 58;
            int porcentaje = 0;

            // Dibujamos la barra del portentaje.
            Console.SetCursorPosition(0, 3);
            Console.Write("0 %                         50 %                       100 %");
            Console.SetCursorPosition(0, 4);
            Console.Write("┌────────────────────────────┬───────────────────────────┐");
            Console.SetCursorPosition(0, 5);
            Console.Write("░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░"); // Ascii 176.
            Console.SetCursorPosition(0, 5);
            Console.ForegroundColor = ConsoleColor.Yellow;

            for (int i = 0; i < barra; i++)
            {
                resultadoPorcentaje = (i + 1.0D) / (barra / 100.0);

                Console.Write("█"); // Muestra ASCII 219 Dec y DB en Hex.
                                    // Console.Write((char)219);
                                    // Console.Write(Encoding.ASCII.GetBytes((char)219));
                porcentaje++; // Incrementa valor.

                PintarCargando(porcentaje);

                Thread.Sleep(100); // 100 ms o 0.1 segundos.
            }

            // Pulse cualquier tecla para salir.
            Console.ReadKey();
        }     

        static void PintarCargando(int porcentaje)
        {
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.SetCursorPosition(0, 1);
            Console.Write("Cargado: " + (resultadoPorcentaje).ToString("N0") + " %");// por dos para que simule el 100%

            // Reestablecemos para que vuelva a pintar bajo la línea de carga.
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.SetCursorPosition(porcentaje, 5);
        }
    }
}


Son menos códigos.

¿Algún programa para capturar imágenes a gif como he visto por aquí?

Muchas gracias a todos.
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/

Eleкtro

Cita de: Meta en  1 Marzo 2019, 05:48 AM
¿Algún programa para capturar imágenes a gif como he visto por aquí?

El que yo uso: https://www.screentogif.com/








Serapis

Cita de: Meta en  1 Marzo 2019, 05:48 AM
Buenas:
...Intenté pasarlo con este enlace, pero me daba errores por todoas partes.
...Son menos códigos....
Cuantas excusas...

He probado con esa página y la verdad que lo hace bastante bien...
Tan solo conviene cambiar los tipos de UInt a int y los float a double.
Luego solo restan 3 conversiones que tratan sobre cadenas... obtener una cadena que consiste de x caracteres, en c# es usar el constructor new string(char, cantidad) (en vb solemos usar strDup, que es el heredero de Strings(char, cantidad)...

Yo no he tardado más de 1 minuto en pasarlo a C# usando el código devuelto por esa página (me reitero, lo hace bastante bien):

Aquí exactamente el mismo código que puse en VB (bueno debajo del progreso he añadido otra línea).
Código (csharp) [Seleccionar]

using System;
using Microsoft.VisualBasic;
using System.Threading;

static class Module1
{
    public static void Main()
    {
        Console.Title = "Simulador barra de progreso";
        Console.WindowWidth = 80;   // X ancho.
        Console.WindowHeight = 20;  // Y altura.
        Console.CursorVisible = false;

        int k;
        Progreso p = new Progreso(0, 58, 0, 5); // por defecto columna 12
        for (k = 0; k <= p.Maximo; k++)
        {
            p.Incrementar();     // incrementa y redibuja todo.
            Thread.Sleep(40);    // 40 milisegundos.
        }

        Console.ReadKey();
    }

    private class Progreso
    {
        private int p_Min, p_Max;
        private int p_Fila, p_Columna;
        private double p_Valor, s_Avance, s_Porcen;
        private string FullProgreso;

        public Progreso(int Min, int Cantidad, int Value, int Fila = 5, int Columna = 12)
        {
            p_Min = Min;
            p_Max = (p_Min + Cantidad - 1);
            p_Valor = Value;
            s_Avance = (Cantidad / (double)100);
            s_Porcen = (100 / (double)Cantidad);
            FullProgreso = new string((char)177, Cantidad);

            p_Fila = Fila;
            p_Columna = Columna;

            this.Dibujar(true);
        }

        public int Maximo
        {
            get
            {
                return p_Max;
            }
        }

        public void Incrementar()
        {
            p_Valor += s_Avance;
            this.Dibujar(false);
        }

        private void Dibujar(bool Previo)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            if ((Previo == true))
            {
                Console.SetCursorPosition(p_Columna, p_Fila - 2);
                Console.Write("0 %                         50 %                     100 %");
                Console.SetCursorPosition(p_Columna - 1, p_Fila - 1);
                Console.Write("{0}{1}{0}", (char)179, new string((char)205,(p_Max - p_Min + 1))); // 205= 2 rayas horizontales 240=1raya horizontal. 179=carácter de puntos (no macizo)
                // dibujamos la misma línea por debajo de la barra de progreso.
                Console.SetCursorPosition(p_Columna - 1, p_Fila + 1);
                Console.Write("{0}{1}{0}", (char)179, new string((char)205, (p_Max - p_Min + 1)));
            }
            Console.SetCursorPosition(p_Columna, p_Fila - 4);
            Console.Write("Cargado: {0} {1}", (p_Valor * s_Porcen / (double)s_Avance).ToString("N2"), " %");
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.SetCursorPosition(p_Columna, p_Fila);
            Console.Write(FullProgreso.Substring(0, Convert.ToInt32 (p_Valor / s_Avance)));
        }
    }
}


Y te repito, que aunque sena apenas 10-15 líneas de código más, resulta más legible y más fácilmente modificable, también es más eficiente... el código de la función dibujar solo dibuja ciertas líneas una única y tan solo en cada ciclo redibuja lo que cambia.



En fin, creo que tu mayor problema es que vas a saltos, no conoces lo esencial del lenguaje, vas aprendiendo a base de tropezarte con las piedras que encuentras en el camino, y en vez de enfrentarte a ellas para apartarlas del camino (esto es entenderlas), tu lo que haces es sortearlas... así que ahí siguen y seguirán pese al tiempo que transcurra.
Al final solo usarás del lenguaje aquello que entiendes, porque lo que no entiendes, te da pereza y huyes de ello. Así no se puede ser programador.
No puedes aprovechar el potencial de un lenguaje si no conoces al menos lo básico. No es que todo deba ser hecho de la mejor manera posible, a veces es más práctico no perder demasiado tiempo en algo a condición de que también resuelva de modo eficiente el problema en cuestión, pero tampoco tendrás opciones para ello, porque las desconoces...

Meta

Cita de: Eleкtro en  1 Marzo 2019, 11:29 AM
El que yo uso: https://www.screentogif.com/

Muchísimas gracias mi muy distinguido amigo. ;)

En cuanto a NEBIRE. ;)
Sigo tropesando. Me dio por comprar un libro en papel barato que me da más motivación para leerlo pero en C/C++, para practicar ejercicios está bien. En C# están libros caros y grandes. Lo de grande está bien pero 80 €urazos como estoy ahora como que no. Se que está internet, también aprovechar.

En cuanto a tu código que funciona bien, en el cual agradezco. Lo entiendo mejor, por que muestras, lo hiciste con estilo y un poco pijo . ;)

En la parte
Código (csharp) [Seleccionar]
FullProgreso = new string((char)177, Cantidad);

Para asegurte que se muestre bien la imágenes dependiendo quien ejecute el programa, puede mostrar diferentes caractéres.

Hay que asegurarse un tipo de codificación, algo parecido a esto.

Código (csharp) [Seleccionar]
Console.Write(Encoding.ASCII.GetBytes((char)219));

Así te aseguras que en cualquier país funcione a la primera.

Gracias por los consejos. ;)
Tutoriales Electrónica y PIC: http://electronica-pic.blogspot.com/