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

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Simulando barra de progreso
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] 2 Ir Abajo Respuesta Imprimir
Autor Tema: Simulando barra de progreso  (Leído 8,938 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Simulando barra de progreso
« en: 27 Febrero 2019, 22:29 pm »

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. ;)


« Última modificación: 28 Febrero 2019, 07:16 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Simulando barra de progreso
« Respuesta #1 en: 28 Febrero 2019, 07:29 am »

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

Citar
Código
  1. int barra = 49;
Citar
Código
  1. for (int i = 0; i <= barra; i++) { ... }

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

Citar
Código
  1. 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
  1. int barra = 58;
  2. double porcentaje = 0;
  3.  
  4. for (int i = 0; i < barra; i++) {
  5. porcentaje = ((i + 1.0D) / (barra / 100.0));
  6. }

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.


« Última modificación: 28 Febrero 2019, 11:19 am por Eleкtro » En línea

Serapis
Colaborador
***
Desconectado Desconectado

Mensajes: 3.351


Ver Perfil
Re: Simulando barra de progreso
« Respuesta #2 en: 28 Febrero 2019, 16:02 pm »

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).
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Simulando barra de progreso
« Respuesta #3 en: 28 Febrero 2019, 16:56 pm »

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
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 12-December-2016
  4. ' ***********************************************************************
  5.  
  6. #Region " Imports "
  7.  
  8. Imports System.Drawing
  9. Imports System.Text
  10. Imports System.Threading
  11.  
  12. ' Imports DevCase.Core.Application.UserInterface.Tools.Console
  13. ' Imports DevCase.Core.Design
  14.  
  15. #End Region
  16.  
  17. #Region " Console ProgressBar "
  18.  
  19. 'Namespace DevCase.Core.Application.UserInterface
  20.  
  21. '#If Not NET40 Then
  22.  
  23. ''' ----------------------------------------------------------------------------------------------------
  24. ''' <summary>
  25. ''' A personalizable colorful ASCII progress bar for console applications.
  26. ''' </summary>
  27. ''' ----------------------------------------------------------------------------------------------------
  28. ''' <remarks>
  29. ''' Based on: <see href="https://gist.github.com/DanielSWolf/0ab6a96899cc5377bf54"/>
  30. ''' </remarks>
  31. ''' ----------------------------------------------------------------------------------------------------
  32. ''' <example> This is a code example.
  33. ''' <code>
  34. ''' Public Module Module1
  35. '''
  36. '''     Public Sub Main()
  37. '''         Console.CursorVisible = False
  38. '''         Console.Write("Performing some task... ")
  39. '''
  40. '''         Using progress As New ConsoleProgressBar(blockCount:=20) With {
  41. '''             .Animation = "||//--\\".ToCharArray(),
  42. '''             .AnimationSpeed = TimeSpan.FromMilliseconds(125),
  43. '''             .AnimationBackColor = Console.BackgroundColor,
  44. '''             .AnimationForeColor = ConsoleColor.Yellow,
  45. '''             .BlockActiveChar = "&#9608;"c,
  46. '''             .BlockInactiveChar = "·"c,
  47. '''             .BlockActiveBackColor = Console.BackgroundColor,
  48. '''             .BlockActiveForeColor = ConsoleColor.Green,
  49. '''             .BlockInactiveBackColor = Console.BackgroundColor,
  50. '''             .BlockInactiveForeColor = ConsoleColor.DarkGray,
  51. '''             .BorderBackColor = Console.BackgroundColor,
  52. '''             .BorderForeColor = ConsoleColor.White,
  53. '''             .ProgressTextFormat = "{1} of {2} ({0}%)",
  54. '''             .ProgressTextBackColor = Console.BackgroundColor,
  55. '''             .ProgressTextForeColor = ConsoleColor.Gray
  56. '''         }
  57. '''
  58. '''             For i As Integer = 0 To 100
  59. '''                 progress.Report(i / 100)
  60. '''                 Thread.Sleep(100)
  61. '''             Next i
  62. '''         End Using
  63. '''
  64. '''         Console.WriteLine()
  65. '''         Console.WriteLine("Done.")
  66. '''         Console.ReadKey()
  67. '''     End Sub
  68. '''
  69. ''' End Module
  70. ''' </code>
  71. ''' </example>
  72. ''' ----------------------------------------------------------------------------------------------------
  73. Public NotInheritable Class ConsoleProgressBar : Implements IDisposable : Implements IProgress(Of Double)
  74.  
  75. #Region " Properties "
  76.  
  77.        ''' ----------------------------------------------------------------------------------------------------
  78.        ''' <summary>
  79.        ''' Gets the current progress value. From 0.0 to 1.0
  80.        ''' </summary>
  81.        ''' ----------------------------------------------------------------------------------------------------
  82.        ''' <value>
  83.        ''' The current progress value. From 0.0 to 1.0
  84.        ''' </value>
  85.        ''' ----------------------------------------------------------------------------------------------------
  86.        Public ReadOnly Property CurrentProgress As Double
  87.            Get
  88.                Return Me.currentProgressB
  89.            End Get
  90.        End Property
  91.        ''' ----------------------------------------------------------------------------------------------------
  92.        ''' <summary>
  93.        ''' The current progress value. From 0.0 to 1.0
  94.        ''' </summary>
  95.        ''' ----------------------------------------------------------------------------------------------------
  96.        Private currentProgressB As Double
  97.  
  98.        ''' ----------------------------------------------------------------------------------------------------
  99.        ''' <summary>
  100.        ''' Gets the amount of blocks to display in the progress bar.
  101.        ''' <para></para>
  102.        ''' Default value is: 20
  103.        ''' </summary>
  104.        ''' ----------------------------------------------------------------------------------------------------
  105.        ''' <value>
  106.        ''' The amount of blocks to display in the progress bar.
  107.        ''' </value>
  108.        ''' ----------------------------------------------------------------------------------------------------
  109.        Public ReadOnly Property BlockCount As Integer
  110.  
  111.        ''' ----------------------------------------------------------------------------------------------------
  112.        ''' <summary>
  113.        ''' Gets the character used to draw an active progress bar block.
  114.        ''' <para></para>
  115.        ''' Default value is: "#"
  116.        ''' </summary>
  117.        ''' ----------------------------------------------------------------------------------------------------
  118.        ''' <value>
  119.        ''' The character used to draw an active progress bar block.
  120.        ''' </value>
  121.        ''' ----------------------------------------------------------------------------------------------------
  122.        Public Property BlockActiveChar As Char
  123.  
  124.        ''' ----------------------------------------------------------------------------------------------------
  125.        ''' <summary>
  126.        ''' Gets the character used to draw an inactive progress bar block.
  127.        ''' <para></para>
  128.        ''' Default value is: "·"
  129.        ''' </summary>
  130.        ''' ----------------------------------------------------------------------------------------------------
  131.        ''' <value>
  132.        ''' The character used to draw an inactive progress bar block.
  133.        ''' </value>
  134.        ''' ----------------------------------------------------------------------------------------------------
  135.        Public Property BlockInactiveChar As Char
  136.  
  137.        ''' ----------------------------------------------------------------------------------------------------
  138.        ''' <summary>
  139.        ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the background of an active progress bar block.
  140.        ''' </summary>
  141.        ''' ----------------------------------------------------------------------------------------------------
  142.        ''' <value>
  143.        ''' The <see cref="ConsoleColor"/> used to paint the background of an active progress bar block.
  144.        ''' </value>
  145.        ''' ----------------------------------------------------------------------------------------------------
  146.        Public Property BlockActiveBackColor As ConsoleColor
  147.  
  148.        ''' ----------------------------------------------------------------------------------------------------
  149.        ''' <summary>
  150.        ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the foreground of an active progress bar block.
  151.        ''' </summary>
  152.        ''' ----------------------------------------------------------------------------------------------------
  153.        ''' <value>
  154.        ''' The <see cref="ConsoleColor"/> used to paint the foreground of an active progress bar block.
  155.        ''' </value>
  156.        ''' ----------------------------------------------------------------------------------------------------
  157.        Public Property BlockActiveForeColor As ConsoleColor
  158.  
  159.        ''' ----------------------------------------------------------------------------------------------------
  160.        ''' <summary>
  161.        ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the background of a inactive progress bar block.
  162.        ''' </summary>
  163.        ''' ----------------------------------------------------------------------------------------------------
  164.        ''' <value>
  165.        ''' The <see cref="ConsoleColor"/> used to paint the background of a inactive progress bar block.
  166.        ''' </value>
  167.        ''' ----------------------------------------------------------------------------------------------------
  168.        Public Property BlockInactiveBackColor As ConsoleColor
  169.  
  170.        ''' ----------------------------------------------------------------------------------------------------
  171.        ''' <summary>
  172.        ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the foreground of a inactive progress bar block.
  173.        ''' </summary>
  174.        ''' ----------------------------------------------------------------------------------------------------
  175.        ''' <value>
  176.        ''' The <see cref="ConsoleColor"/> used to paint the foreground of a inactive progress bar block.
  177.        ''' </value>
  178.        ''' ----------------------------------------------------------------------------------------------------
  179.        Public Property BlockInactiveForeColor As ConsoleColor
  180.  
  181.        ''' ----------------------------------------------------------------------------------------------------
  182.        ''' <summary>
  183.        ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the background of the borders of the progress bar.
  184.        ''' </summary>
  185.        ''' ----------------------------------------------------------------------------------------------------
  186.        ''' <value>
  187.        ''' The <see cref="ConsoleColor"/> used to paint the background of the borders of the progress bar.
  188.        ''' </value>
  189.        ''' ----------------------------------------------------------------------------------------------------
  190.        Public Property BorderBackColor As ConsoleColor
  191.  
  192.        ''' ----------------------------------------------------------------------------------------------------
  193.        ''' <summary>
  194.        ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the foreground of the borders of the progress bar.
  195.        ''' </summary>
  196.        ''' ----------------------------------------------------------------------------------------------------
  197.        ''' <value>
  198.        ''' The <see cref="ConsoleColor"/> used to paint the foreground of the borders of the progress bar.
  199.        ''' </value>
  200.        ''' ----------------------------------------------------------------------------------------------------
  201.        Public Property BorderForeColor As ConsoleColor
  202.  
  203.        ''' ----------------------------------------------------------------------------------------------------
  204.        ''' <summary>
  205.        ''' Gets or sets the format of the progress text, where:
  206.        ''' <para></para> {0} = Percentage Value
  207.        ''' <para></para> {1} = Current Value
  208.        ''' <para></para> {2} = Maximum Value
  209.        ''' <para></para>
  210.        ''' Default value is: "{0}%"
  211.        ''' </summary>
  212.        ''' ----------------------------------------------------------------------------------------------------
  213.        ''' <value>
  214.        ''' The format of the percentage string.
  215.        ''' </value>
  216.        ''' ----------------------------------------------------------------------------------------------------
  217.        Public Property ProgressTextFormat As String
  218.  
  219.        ''' ----------------------------------------------------------------------------------------------------
  220.        ''' <summary>
  221.        ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the background of the progress text.
  222.        ''' </summary>
  223.        ''' ----------------------------------------------------------------------------------------------------
  224.        ''' <value>
  225.        ''' The <see cref="ConsoleColor"/> used to paint the background of the borders of the progress text.
  226.        ''' </value>
  227.        ''' ----------------------------------------------------------------------------------------------------
  228.        Public Property ProgressTextBackColor As ConsoleColor
  229.  
  230.        ''' ----------------------------------------------------------------------------------------------------
  231.        ''' <summary>
  232.        ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the foreground of the borders of the progress text.
  233.        ''' </summary>
  234.        ''' ----------------------------------------------------------------------------------------------------
  235.        ''' <value>
  236.        ''' The <see cref="ConsoleColor"/> used to paint the foreground of the borders of the progress text.
  237.        ''' </value>
  238.        ''' ----------------------------------------------------------------------------------------------------
  239.        Public Property ProgressTextForeColor As ConsoleColor
  240.  
  241.        ''' ----------------------------------------------------------------------------------------------------
  242.        ''' <summary>
  243.        ''' Gets or sets the characters used to draw the animation secuence at the very end of the progress bar.
  244.        ''' <para></para>
  245.        ''' Default value is: {"|"c, "|"c, "/"c, "/"c, "-"c, "-"c, "\"c, "\"c}  ( that is: "||//--\\" )
  246.        ''' </summary>
  247.        ''' ----------------------------------------------------------------------------------------------------
  248.        ''' <value>
  249.        ''' The characters used to draw the animation secuence at the very end of the progress bar.
  250.        ''' </value>
  251.        ''' ----------------------------------------------------------------------------------------------------
  252.        Public Property Animation As Char()
  253.  
  254.        ''' ----------------------------------------------------------------------------------------------------
  255.        ''' <summary>
  256.        ''' Gets or sets the speed (framerate) of the animation secuence defined in <see cref="ConsoleProgressBar.Animation"/>.
  257.        ''' <para></para>
  258.        ''' Default value is: 125 milliseconds.
  259.        ''' </summary>
  260.        ''' ----------------------------------------------------------------------------------------------------
  261.        ''' <value>
  262.        ''' The speed (framerate) of the animation secuence defined in <see cref="ConsoleProgressBar.Animation"/>.
  263.        ''' </value>
  264.        ''' ----------------------------------------------------------------------------------------------------
  265.        Public Property AnimationSpeed As TimeSpan
  266.  
  267.        ''' ----------------------------------------------------------------------------------------------------
  268.        ''' <summary>
  269.        ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the background of the animation secuence.
  270.        ''' </summary>
  271.        ''' ----------------------------------------------------------------------------------------------------
  272.        ''' <value>
  273.        ''' The <see cref="ConsoleColor"/> used to paint the background of the borders of the animation secuence.
  274.        ''' </value>
  275.        ''' ----------------------------------------------------------------------------------------------------
  276.        Public Property AnimationBackColor As ConsoleColor
  277.  
  278.        ''' ----------------------------------------------------------------------------------------------------
  279.        ''' <summary>
  280.        ''' Gets or sets the <see cref="ConsoleColor"/> used to paint the foreground of the borders of the animation secuence.
  281.        ''' </summary>
  282.        ''' ----------------------------------------------------------------------------------------------------
  283.        ''' <value>
  284.        ''' The <see cref="ConsoleColor"/> used to paint the foreground of the borders of the animation secuence.
  285.        ''' </value>
  286.        ''' ----------------------------------------------------------------------------------------------------
  287.        Public Property AnimationForeColor As ConsoleColor
  288.  
  289.        ''' ----------------------------------------------------------------------------------------------------
  290.        ''' <summary>
  291.        ''' Gets or sets a value indicating whether the animation secuence is visible in the progress bar.
  292.        ''' </summary>
  293.        ''' ----------------------------------------------------------------------------------------------------
  294.        ''' <value>
  295.        ''' A value indicating whether the animation secuence is visible in the progress bar.
  296.        ''' </value>
  297.        ''' ----------------------------------------------------------------------------------------------------
  298.        Public Property AnimationVisible As Boolean
  299.  
  300. #End Region
  301.  
  302. #Region " Private Fields "
  303.  
  304.        ''' ----------------------------------------------------------------------------------------------------
  305.        ''' <summary>
  306.        ''' The timer.
  307.        ''' </summary>
  308.        ''' ----------------------------------------------------------------------------------------------------
  309.        Private ReadOnly timer As Threading.Timer
  310.  
  311.        ''' ----------------------------------------------------------------------------------------------------
  312.        ''' <summary>
  313.        ''' The current animation index.
  314.        ''' </summary>
  315.        ''' ----------------------------------------------------------------------------------------------------
  316.        Private animationIndex As Integer
  317.  
  318.        ''' ----------------------------------------------------------------------------------------------------
  319.        ''' <summary>
  320.        ''' The cursor position in the console buffer when instancing the <see cref="ConsoleProgressBar"/> class.
  321.        ''' </summary>
  322.        ''' ----------------------------------------------------------------------------------------------------
  323.        Private cursorPos As Point
  324.  
  325. #End Region
  326.  
  327. #Region " Constructors "
  328.  
  329.        ''' ----------------------------------------------------------------------------------------------------
  330.        ''' <summary>
  331.        ''' Prevents a default instance of the <see cref="ConsoleProgressBar"/> class from being created.
  332.        ''' </summary>
  333.        ''' ----------------------------------------------------------------------------------------------------
  334.        Private Sub New()
  335.        End Sub
  336.  
  337.        ''' ----------------------------------------------------------------------------------------------------
  338.        ''' <summary>
  339.        ''' Initializes a new instance of the <see cref="ConsoleProgressBar"/> class.
  340.        ''' </summary>
  341.        ''' ----------------------------------------------------------------------------------------------------
  342.        ''' <param name="blockCount">
  343.        ''' The amount of blocks to display in the progress bar. Default value is: 20
  344.        ''' </param>
  345.        ''' ----------------------------------------------------------------------------------------------------
  346.        Public Sub New(Optional ByVal blockCount As Integer = 10)
  347.  
  348.            If (blockCount < 2) Then
  349.                Throw New ArgumentException(message:="Block count must be a value greater than 1.", paramName:=NameOf(blockCount))
  350.            End If
  351.  
  352.            Me.BlockCount = blockCount
  353.            Me.BlockActiveChar = "#"c
  354.            Me.BlockInactiveChar = "·"c
  355.  
  356.            Me.BlockActiveBackColor = Console.BackgroundColor
  357.            Me.BlockActiveForeColor = Console.ForegroundColor
  358.            Me.BlockInactiveBackColor = Console.BackgroundColor
  359.            Me.BlockInactiveForeColor = Console.ForegroundColor
  360.            Me.BorderBackColor = Console.BackgroundColor
  361.            Me.BorderForeColor = Console.ForegroundColor
  362.  
  363.            Me.Animation = "||//--\\".ToCharArray()
  364.            Me.AnimationSpeed = TimeSpan.FromMilliseconds(100)
  365.            Me.AnimationVisible = True
  366.            Me.AnimationBackColor = Console.BackgroundColor
  367.            Me.AnimationForeColor = Console.ForegroundColor
  368.  
  369.            Me.ProgressTextFormat = "{0}%"
  370.            Me.ProgressTextBackColor = Console.BackgroundColor
  371.            Me.ProgressTextForeColor = Console.ForegroundColor
  372.  
  373.            Me.timer = New Timer(AddressOf Me.TimerCallback)
  374.  
  375.            Me.cursorPos = New Point(Console.CursorLeft, Console.CursorTop)
  376.  
  377.            ' A progress bar is only for temporary display in a console window.
  378.            ' If the console output is redirected to a text file, draw nothing.
  379.            ' Otherwise, we will end up with a lot of garbage in the target text file.
  380.            If Not Console.IsOutputRedirected Then
  381.                Me.ResetTimer()
  382.            End If
  383.  
  384.        End Sub
  385.  
  386. #End Region
  387.  
  388. #Region " Public Methods "
  389.  
  390.        ''' ----------------------------------------------------------------------------------------------------
  391.        ''' <summary>
  392.        ''' Reports a progress update.
  393.        ''' </summary>
  394.        ''' ----------------------------------------------------------------------------------------------------
  395.        ''' <param name="value">
  396.        ''' The value of the updated progress.
  397.        ''' </param>
  398.        ''' ----------------------------------------------------------------------------------------------------
  399.        Public Sub Report(ByVal value As Double) Implements IProgress(Of Double).Report
  400.            ' Make sure value is in [0..1] range
  401.            value = Math.Max(0, Math.Min(1, value))
  402.            Interlocked.Exchange(Me.currentProgressB, value)
  403.        End Sub
  404.  
  405. #End Region
  406.  
  407. #Region " Private Methods "
  408.  
  409.        ''' ----------------------------------------------------------------------------------------------------
  410.        ''' <summary>
  411.        ''' Handles the calls from <see cref="ConsoleProgressBar.timer"/>.
  412.        ''' </summary>
  413.        ''' ----------------------------------------------------------------------------------------------------
  414.        ''' <param name="state">
  415.        ''' An object containing application-specific information relevant to the
  416.        ''' method invoked by this delegate, or <see langword="Nothing"/>.
  417.        ''' </param>
  418.        ''' ----------------------------------------------------------------------------------------------------
  419.        Private Sub TimerCallback(ByVal state As Object)
  420.  
  421.            SyncLock Me.timer
  422.                If (Me.isDisposed) Then
  423.                    Exit Sub
  424.                End If
  425.  
  426.                Me.UpdateText()
  427.                Me.ResetTimer()
  428.            End SyncLock
  429.  
  430.        End Sub
  431.  
  432.        ''' ----------------------------------------------------------------------------------------------------
  433.        ''' <summary>
  434.        ''' Resets the timer.
  435.        ''' </summary>
  436.        ''' ----------------------------------------------------------------------------------------------------
  437.        Private Sub ResetTimer()
  438.            Me.timer.Change(Me.AnimationSpeed, TimeSpan.FromMilliseconds(-1))
  439.        End Sub
  440.  
  441.        ''' ----------------------------------------------------------------------------------------------------
  442.        ''' <summary>
  443.        ''' Updates the progress bar text.
  444.        ''' </summary>
  445.        ''' ----------------------------------------------------------------------------------------------------
  446.        Private Sub UpdateText()
  447.  
  448.            Dim currentBlockCount As Integer = CInt(Me.currentProgressB * Me.BlockCount)
  449.            Dim percent As Integer = CInt(Me.currentProgressB * 100)
  450.  
  451.            Dim text As String =
  452.                    String.Format("[{0}{1}] {2} {3}",
  453.                                  New String(Me.BlockActiveChar, currentBlockCount),
  454.                                  New String(Me.BlockInactiveChar, Me.BlockCount - currentBlockCount),
  455.                                  String.Format(Me.ProgressTextFormat, percent, (Me.currentProgressB * 100), 100),
  456.                                  Me.Animation(Math.Max(Interlocked.Increment(Me.animationIndex), Me.animationIndex - 1) Mod Me.Animation.Length))
  457.            Dim textLen As Integer = text.Length
  458.  
  459.            Dim coloredText As New StringBuilder()
  460.            With coloredText
  461.                .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.BorderBackColor), CInt(Me.BorderForeColor),
  462.                                  "[")
  463.  
  464.                .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.BlockActiveBackColor), CInt(Me.BlockActiveForeColor),
  465.                                  New String(Me.BlockActiveChar, currentBlockCount))
  466.  
  467.                .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.BlockInactiveBackColor), CInt(Me.BlockInactiveForeColor),
  468.                                  New String(Me.BlockInactiveChar, Me.BlockCount - currentBlockCount))
  469.  
  470.                .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.BorderBackColor), CInt(Me.BorderForeColor),
  471.                                  "]")
  472.                .Append(" ")
  473.                .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.ProgressTextBackColor), CInt(Me.ProgressTextForeColor),
  474.                                  String.Format(Me.ProgressTextFormat, percent, (Me.currentProgressB * 100), 100))
  475.  
  476.                .Append(" ")
  477.                If Me.AnimationVisible Then
  478.                    .AppendFormat("*B{0}**F{1}*{2}*-B**-F*", CInt(Me.AnimationBackColor), CInt(Me.AnimationForeColor),
  479.                                      Me.Animation(Math.Max(Interlocked.Increment(Me.animationIndex), Me.animationIndex - 1) Mod Me.Animation.Length))
  480.                End If
  481.            End With
  482.  
  483.            ' Lazy error handling when the console window is resized by the end-user.
  484.            Try
  485.                If (Console.BufferWidth > textLen) Then
  486.                    coloredText.Append(" "c, Console.BufferWidth - text.Length)
  487.                End If
  488.                Console.SetCursorPosition(Me.cursorPos.X, Me.cursorPos.Y)
  489.                ConsoleUtil.WriteColorText(coloredText.ToString(), {"*"c})
  490.  
  491.            Catch ex As Exception
  492.                ' Do nothing.
  493.            End Try
  494.  
  495.        End Sub
  496.  
  497. #End Region
  498.  
  499. #Region " IDisposable Implementation "
  500.  
  501.        ''' ----------------------------------------------------------------------------------------------------
  502.        ''' <summary>
  503.        ''' Flag to detect redundant calls when disposing.
  504.        ''' </summary>
  505.        ''' ----------------------------------------------------------------------------------------------------
  506.        Private isDisposed As Boolean = False
  507.  
  508.        ''' ----------------------------------------------------------------------------------------------------
  509.        ''' <summary>
  510.        ''' Releases all the resources used by this instance.
  511.        ''' </summary>
  512.        ''' ----------------------------------------------------------------------------------------------------
  513.        <DebuggerStepThrough>
  514.        Public Sub Dispose() Implements IDisposable.Dispose
  515.            Me.Dispose(isDisposing:=True)
  516.        End Sub
  517.  
  518.        ''' ----------------------------------------------------------------------------------------------------
  519.        ''' <summary>
  520.        ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  521.        ''' Releases unmanaged and, optionally, managed resources.
  522.        ''' </summary>
  523.        ''' ----------------------------------------------------------------------------------------------------
  524.        ''' <param name="isDisposing">
  525.        ''' <see langword="True"/>  to release both managed and unmanaged resources;
  526.        ''' <see langword="False"/> to release only unmanaged resources.
  527.        ''' </param>
  528.        ''' ----------------------------------------------------------------------------------------------------
  529.        <DebuggerStepThrough>
  530.        Protected Sub Dispose(ByVal isDisposing As Boolean)
  531.  
  532.            If (Not Me.isDisposed) AndAlso (isDisposing) Then
  533.                SyncLock Me.timer
  534.                    Me.UpdateText()
  535.                End SyncLock
  536.                If (Me.timer IsNot Nothing) Then
  537.                    Me.timer.Dispose()
  538.                End If
  539.            End If
  540.  
  541.            Me.isDisposed = True
  542.  
  543.        End Sub
  544.  
  545. #End Region
  546.  
  547.    End Class
  548.  
  549. '#End If
  550.  
  551. 'End Namespace
  552.  
  553. #End Region
  554.  
  555. 'Namespace DevCase.Core.Application.UserInterface.Tools.Console
  556.  
  557. Public NotInheritable Class ConsoleUtil
  558.  
  559. #Region " Public Methods "
  560.  
  561.    ''' ----------------------------------------------------------------------------------------------------
  562.    ''' <summary>
  563.    ''' Writes colored text to the console.
  564.    ''' <para></para>
  565.    ''' Use <c>*F##*</c> as the start delimiter of the ForeColor, use <c>*-F*</c> as the end delimiter of the ForeColor.
  566.    ''' <para></para>
  567.    ''' Use <c>*B##*</c> as the start delimiter of the BackColor, use <c>*-B*</c> as the end delimiter of the BackColor.
  568.    ''' </summary>
  569.    ''' ----------------------------------------------------------------------------------------------------
  570.    ''' <example> This is a code example.
  571.    ''' <code>
  572.    ''' WriteColorText("*F10*Hello *F14*World!*-F*", {"*"c})
  573.    ''' </code>
  574.    ''' </example>
  575.    ''' ----------------------------------------------------------------------------------------------------
  576.    ''' <param name="text">
  577.    ''' The color-delimited text to write.
  578.    ''' </param>
  579.    '''
  580.    ''' <param name="delimiters">
  581.    ''' A set of 1 or 2 delimiters to parse the color-delimited string.
  582.    ''' </param>
  583.    ''' ----------------------------------------------------------------------------------------------------
  584.    <DebuggerStepThrough>
  585.    Public Shared Sub WriteColorText(ByVal text As String,
  586.                                         ByVal delimiters As Char())
  587.  
  588.        ' Save the current console colors to later restore them.
  589.        Dim oldForedColor As ConsoleColor = Console.ForegroundColor
  590.        Dim oldBackColor As ConsoleColor = Console.BackgroundColor
  591.  
  592.        ' Split the string to retrieve and parse the color-delimited strings.
  593.        Dim stringParts As String() =
  594.                    text.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  595.  
  596.        ' Parse the string parts.
  597.        For Each part As String In stringParts
  598.  
  599.            If (part.ToUpper Like "F#") OrElse (part.ToUpper Like "F##") Then
  600.                ' Use the new ForeColor.
  601.                Console.ForegroundColor = DirectCast(CInt(part.Substring(1)), ConsoleColor)
  602.  
  603.            ElseIf (part.ToUpper Like "B#") OrElse (part.ToUpper Like "B##") Then
  604.                ' Use the new BackgroundColor.
  605.                Console.BackgroundColor = DirectCast(CInt(part.Substring(1)), ConsoleColor)
  606.  
  607.            ElseIf (part.ToUpper Like "-F") Then
  608.                ' Use the saved Forecolor.
  609.                Console.ForegroundColor = oldForedColor
  610.  
  611.            ElseIf (part.ToUpper Like "-B") Then
  612.                ' Use the saved BackgroundColor.
  613.                Console.BackgroundColor = oldBackColor
  614.  
  615.            Else ' String part is not a delimiter so we can print it.
  616.                Console.Write(part)
  617.  
  618.            End If
  619.  
  620.        Next part
  621.  
  622.        ' Restore the saved console colors.
  623.        Console.ForegroundColor = oldForedColor
  624.        Console.BackgroundColor = oldBackColor
  625.  
  626.    End Sub
  627.  
  628. #End Region
  629.  
  630.    Private Sub New()
  631.    End Sub
  632.  
  633. End Class
  634.  
  635. 'End Namespace

Modo de empleo:
Código
  1. Public Module Module1
  2.  
  3.    Public Sub Main()
  4.        Console.CursorVisible = False
  5.        Console.Write("Performing some task... ")
  6.  
  7.        Using progress As New ConsoleProgressBar(blockCount:=20) With {
  8.            .Animation = "||//--\\".ToCharArray(),
  9.            .AnimationSpeed = TimeSpan.FromMilliseconds(125),
  10.            .AnimationBackColor = Console.BackgroundColor,
  11.            .AnimationForeColor = ConsoleColor.Yellow,
  12.            .BlockActiveChar = "&#9608;"c,
  13.            .BlockInactiveChar = "·"c,
  14.            .BlockActiveBackColor = Console.BackgroundColor,
  15.            .BlockActiveForeColor = ConsoleColor.Green,
  16.            .BlockInactiveBackColor = Console.BackgroundColor,
  17.            .BlockInactiveForeColor = ConsoleColor.DarkGray,
  18.            .BorderBackColor = Console.BackgroundColor,
  19.            .BorderForeColor = ConsoleColor.White,
  20.            .ProgressTextFormat = "{1} of {2} ({0}%)",
  21.            .ProgressTextBackColor = Console.BackgroundColor,
  22.            .ProgressTextForeColor = ConsoleColor.Gray
  23.        }
  24.  
  25.            For i As Integer = 0 To 100
  26.                progress.Report(i / 100)
  27.                Thread.Sleep(100)
  28.            Next i
  29.        End Using
  30.  
  31.        Console.WriteLine()
  32.        Console.WriteLine("Done.")
  33.        Console.ReadKey()
  34.    End Sub
  35.  
  36. 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...
« Última modificación: 28 Febrero 2019, 17:14 pm por Eleкtro » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Simulando barra de progreso
« Respuesta #4 en: 28 Febrero 2019, 18:02 pm »

Buenas gente.

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

Código
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Barra_progreso_consola_01_cs
  5. {
  6.    class Program
  7.    {
  8.        static void Main(string[] args)
  9.        {
  10.            // Título de la ventana.
  11.            Console.Title = "Simulaor barra";
  12.  
  13.            // Tamaño ventana consola.
  14.            Console.WindowWidth = 60; // X ancho.
  15.            Console.WindowHeight = 20; // Y altura.
  16.  
  17.            // Cursor invisible.
  18.            Console.CursorVisible = false;
  19.  
  20.            // Variables.
  21.            int barra = 58;
  22.            double porcentaje = 0;
  23.  
  24.            Console.SetCursorPosition(17, 1);
  25.            Console.Write("    ");
  26.            Console.SetCursorPosition(17, 1);
  27.            Console.Write("");
  28.  
  29.            // Dibujamos la barra del portentaje.
  30.            Console.SetCursorPosition(0, 3);
  31.            Console.Write("0 %                         50 %                       100 %");
  32.            Console.SetCursorPosition(0, 4);
  33.            Console.Write("&#9484;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9516;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;");
  34.            //Console.SetCursorPosition(0, 5);
  35.            //Console.ForegroundColor = ConsoleColor.Yellow;
  36.  
  37.            // Barra de progreso.
  38.            for (int i = 0; i <= barra; i++)
  39.            {
  40.                porcentaje = ((i + 1.0D) / (barra / 100.0));
  41.                Console.Write("&#9608;"); // Muestra ASCII 219 Dec y DB en Hex.
  42.                                    // Console.Write((char)219);
  43.                                    // Console.Write(Encoding.ASCII.GetBytes((char)219));
  44.                porcentaje++; // Incrementa valor.
  45.  
  46.                printCargando(porcentaje);
  47.  
  48.                Thread.Sleep(20); // 100 ms o 0.1 segundos.
  49.            }
  50.  
  51.            Console.ReadKey();
  52.        }
  53.  
  54.        static void printCargando(double porcentaje)
  55.        {
  56.            Console.ForegroundColor = ConsoleColor.Gray;
  57.            Console.SetCursorPosition(0, 1);
  58.            // Por dos para que simule el 100%.
  59.            Console.Write("Cargado: " + (porcentaje).ToString("N2") + " %");
  60.            //Console.Write("Cargado: {0} %", (porcentaje).ToString("N2"));
  61.            //Console.Write($"Cargado: { (porcentaje).ToString() } %");
  62.  
  63.            // Reestablecemos para que vuelva a imprimir bajo la línea de carga.
  64.            Console.ForegroundColor = ConsoleColor.Yellow;
  65.            Console.SetCursorPosition(0, 5);
  66.        }
  67.    }
  68. }
  69.  

Esto si que es una buena barra de progreso.


Buen trabajo, lo haré cuando pueda.
« Última modificación: 28 Febrero 2019, 18:15 pm por Meta » En línea

Serapis
Colaborador
***
Desconectado Desconectado

Mensajes: 3.351


Ver Perfil
Re: Simulando barra de progreso
« Respuesta #5 en: 1 Marzo 2019, 02:59 am »

...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
  1. Imports System.Threading
  2.  
  3. Module Module1
  4.    Sub Main()
  5.        Console.Title = "Simulador barra de progreso"
  6.        Console.WindowWidth = 80   ' X ancho.
  7.        Console.WindowHeight = 20  ' Y altura.
  8.        Console.CursorVisible = False  
  9.  
  10.        Dim k As UInteger
  11.        Dim p As Progreso = New Progreso(0, 58, 0, 5) ' por defecto columna 12
  12.        For k = 0 To p.Maximo
  13.            p.Incrementar()     ' incrementa y redibuja todo.
  14.            Thread.Sleep(40)    ' 40 milisegundos.
  15.        Next
  16.  
  17.        Console.ReadKey()
  18.    End Sub
  19.  
  20.    Private Class Progreso
  21.        Dim p_Min, p_Max As UInteger
  22.        Dim p_Fila, p_Columna As UInteger
  23.        Dim p_Valor, s_Avance, s_Porcen As Single
  24.        Dim FullProgreso As String
  25.  
  26.        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)
  27.            p_Min = Min
  28.            p_Max = (p_Min + Cantidad - 1)
  29.            p_Valor = Value
  30.            s_Avance = (Cantidad / 100)
  31.            s_Porcen = (100 / Cantidad)
  32.            FullProgreso = Strings.StrDup(Integer.Parse(Cantidad), Chr(177)) ' 219
  33.  
  34.            p_Fila = Fila
  35.            p_Columna = Columna
  36.  
  37.            Me.Dibujar(True)
  38.        End Sub
  39.  
  40.        Public ReadOnly Property Maximo As UInteger
  41.            Get
  42.                Return p_Max
  43.            End Get
  44.        End Property
  45.  
  46.        Public Sub Incrementar()
  47.            p_Valor += s_Avance
  48.            Me.Dibujar(False)
  49.        End Sub
  50.  
  51.        Private Sub Dibujar(ByVal Previo As Boolean)
  52.            Console.ForegroundColor = ConsoleColor.Red
  53.            If (Previo = True) Then          ' Dibujamos la barra del portentaje.              
  54.                Console.SetCursorPosition(p_Columna, p_Fila - 2)
  55.                Console.Write("0 %                         50 %                     100 %")
  56.                Console.SetCursorPosition(p_Columna - 1, p_Fila - 1)
  57.                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)
  58.            End If
  59.            Console.SetCursorPosition(p_Columna, p_Fila - 4)
  60.            Console.Write("Cargado: {0} {1}", (p_Valor * s_Porcen / s_Avance).ToString("N2"), " %")
  61.            Console.ForegroundColor = ConsoleColor.Yellow
  62.            Console.SetCursorPosition(p_Columna, p_Fila)
  63.            Console.Write(FullProgreso.Substring(0, (p_Valor / s_Avance)))
  64.        End Sub
  65.  
  66.        ' No se usa en este ejemplo
  67.        'Public WriteOnly Property Valor() As UInteger
  68.        '    Set(ByVal value As UInteger)
  69.        '        p_Valor = value
  70.        '        Me.Dibujar(False)
  71.        '    End Set
  72.        'End Property
  73.    End Class
  74. End Module
  75.  

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

« Última modificación: 1 Marzo 2019, 03:19 am por NEBIRE » En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Simulando barra de progreso
« Respuesta #6 en: 1 Marzo 2019, 05:48 am »

Buenas:

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

Al final ya me sale.



Código
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Barra_progreso_consola_03_cs
  5. {
  6.    class Program
  7.    {
  8.        // Variable.
  9.        static double resultadoPorcentaje;
  10.  
  11.        static void Main(string[] args)
  12.        {
  13.            Console.Title = "Simulador barra de progreso";
  14.            Console.WindowWidth = 60;   // X ancho.
  15.            Console.WindowHeight = 10;  // Y altura.
  16.            Console.CursorVisible = false;
  17.  
  18.            // Variable.
  19.            int barra = 58;
  20.            int porcentaje = 0;
  21.  
  22.            // Dibujamos la barra del portentaje.
  23.            Console.SetCursorPosition(0, 3);
  24.            Console.Write("0 %                         50 %                       100 %");
  25.            Console.SetCursorPosition(0, 4);
  26.            Console.Write("&#9484;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9516;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;");
  27.            Console.SetCursorPosition(0, 5);
  28.            Console.Write("&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;&#9617;"); // Ascii 176.
  29.            Console.SetCursorPosition(0, 5);
  30.            Console.ForegroundColor = ConsoleColor.Yellow;
  31.  
  32.            for (int i = 0; i < barra; i++)
  33.            {
  34.                resultadoPorcentaje = (i + 1.0D) / (barra / 100.0);
  35.  
  36.                Console.Write("&#9608;"); // Muestra ASCII 219 Dec y DB en Hex.
  37.                                    // Console.Write((char)219);
  38.                                    // Console.Write(Encoding.ASCII.GetBytes((char)219));
  39.                porcentaje++; // Incrementa valor.
  40.  
  41.                PintarCargando(porcentaje);
  42.  
  43.                Thread.Sleep(100); // 100 ms o 0.1 segundos.
  44.            }
  45.  
  46.            // Pulse cualquier tecla para salir.
  47.            Console.ReadKey();
  48.        }      
  49.  
  50.        static void PintarCargando(int porcentaje)
  51.        {
  52.            Console.ForegroundColor = ConsoleColor.Gray;
  53.            Console.SetCursorPosition(0, 1);
  54.            Console.Write("Cargado: " + (resultadoPorcentaje).ToString("N0") + " %");// por dos para que simule el 100%
  55.  
  56.            // Reestablecemos para que vuelva a pintar bajo la línea de carga.
  57.            Console.ForegroundColor = ConsoleColor.Yellow;
  58.            Console.SetCursorPosition(porcentaje, 5);
  59.        }
  60.    }
  61. }
  62.  

Son menos códigos.

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

Muchas gracias a todos.
« Última modificación: 1 Marzo 2019, 06:08 am por Meta » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Simulando barra de progreso
« Respuesta #7 en: 1 Marzo 2019, 11:29 am »

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

El que yo uso: https://www.screentogif.com/
En línea

Serapis
Colaborador
***
Desconectado Desconectado

Mensajes: 3.351


Ver Perfil
Re: Simulando barra de progreso
« Respuesta #8 en: 1 Marzo 2019, 16:23 pm »

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
  1. using System;
  2. using Microsoft.VisualBasic;
  3. using System.Threading;
  4.  
  5. static class Module1
  6. {
  7.    public static void Main()
  8.    {
  9.        Console.Title = "Simulador barra de progreso";
  10.        Console.WindowWidth = 80;   // X ancho.
  11.        Console.WindowHeight = 20;  // Y altura.
  12.        Console.CursorVisible = false;
  13.  
  14.        int k;
  15.        Progreso p = new Progreso(0, 58, 0, 5); // por defecto columna 12
  16.        for (k = 0; k <= p.Maximo; k++)
  17.        {
  18.            p.Incrementar();     // incrementa y redibuja todo.
  19.            Thread.Sleep(40);    // 40 milisegundos.
  20.        }
  21.  
  22.        Console.ReadKey();
  23.    }
  24.  
  25.    private class Progreso
  26.    {
  27.        private int p_Min, p_Max;
  28.        private int p_Fila, p_Columna;
  29.        private double p_Valor, s_Avance, s_Porcen;
  30.        private string FullProgreso;
  31.  
  32.        public Progreso(int Min, int Cantidad, int Value, int Fila = 5, int Columna = 12)
  33.        {
  34.            p_Min = Min;
  35.            p_Max = (p_Min + Cantidad - 1);
  36.            p_Valor = Value;
  37.            s_Avance = (Cantidad / (double)100);
  38.            s_Porcen = (100 / (double)Cantidad);
  39.            FullProgreso = new string((char)177, Cantidad);
  40.  
  41.            p_Fila = Fila;
  42.            p_Columna = Columna;
  43.  
  44.            this.Dibujar(true);
  45.        }
  46.  
  47.        public int Maximo
  48.        {
  49.            get
  50.            {
  51.                return p_Max;
  52.            }
  53.        }
  54.  
  55.        public void Incrementar()
  56.        {
  57.            p_Valor += s_Avance;
  58.            this.Dibujar(false);
  59.        }
  60.  
  61.        private void Dibujar(bool Previo)
  62.        {
  63.            Console.ForegroundColor = ConsoleColor.Red;
  64.            if ((Previo == true))
  65.            {
  66.                Console.SetCursorPosition(p_Columna, p_Fila - 2);
  67.                Console.Write("0 %                         50 %                     100 %");
  68.                Console.SetCursorPosition(p_Columna - 1, p_Fila - 1);
  69.                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)
  70.                // dibujamos la misma línea por debajo de la barra de progreso.
  71.                Console.SetCursorPosition(p_Columna - 1, p_Fila + 1);
  72.                Console.Write("{0}{1}{0}", (char)179, new string((char)205, (p_Max - p_Min + 1)));
  73.            }
  74.            Console.SetCursorPosition(p_Columna, p_Fila - 4);
  75.            Console.Write("Cargado: {0} {1}", (p_Valor * s_Porcen / (double)s_Avance).ToString("N2"), " %");
  76.            Console.ForegroundColor = ConsoleColor.Yellow;
  77.            Console.SetCursorPosition(p_Columna, p_Fila);
  78.            Console.Write(FullProgreso.Substring(0, Convert.ToInt32 (p_Valor / s_Avance)));
  79.        }
  80.    }
  81. }
  82.  

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...
En línea

Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Simulando barra de progreso
« Respuesta #9 en: 2 Marzo 2019, 22:01 pm »


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
  1. 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
  1. Console.Write(Encoding.ASCII.GetBytes((char)219));

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

Gracias por los consejos. ;)
En línea

Páginas: [1] 2 Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
ARCHIVOS .BAT + BARRA DE PROGRESO
Scripting
martinsan99 7 20,188 Último mensaje 25 Mayo 2007, 18:43 pm
por pantocrator
Hacer una barra de progreso en C#
.NET (C#, VB.NET, ASP)
nico56 5 14,539 Último mensaje 28 Diciembre 2009, 06:37 am
por nico56
barra de progreso
.NET (C#, VB.NET, ASP)
DaNuK 2 4,228 Último mensaje 10 Marzo 2010, 02:05 am
por DaNuK
VBS barra de progreso
Programación Visual Basic
quico5 0 3,217 Último mensaje 14 Agosto 2012, 20:41 pm
por quico5
barra de progreso en c++
Programación C/C++
d91 4 4,872 Último mensaje 27 Abril 2014, 21:25 pm
por amchacon
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines