Simulando barra de progreso
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.
Código:
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. ;)
Eleкtro:
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
int barra = 49;
Citar
Código
for (int i = 0; i <= barra; i++) { ... }
La longitud de caracteres de esa "barra de progreso" son 58, no 49...
Citar
Código
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
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.
Código:
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:
Si es que...
Aquí publicaste un tema relacionado en el año 2016:
Tema: Añadir porcentaje al progressBar
Y aquí otro en el 2017:
Tema: Calcular porcentaje
...
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:
https://gist.github.com/DanielSWolf/0ab6a96899cc5377bf54
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
' ***********************************************************************
' 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
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:
Buenas gente.
He hecho esto gracia a ustedes y no me dibuja la línea.
Código
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.
Navegación
[#] Página Siguiente