Uso de Visual C# para crear una barra de progreso fluida

En este artículo se proporciona información sobre cómo crear un control UserControl personalizado para crear un control ProgressBar de desplazamiento suave.

Versión original del producto: Visual C#
Número de KB original: 323116

Resumen

En este artículo se muestra cómo crear un UserControl personalizado y sencillo para crear un control ProgressBar de desplazamiento suave.

En versiones anteriores del control ProgressBar, como la versión que se proporciona con el control ActiveX controles comunes de Microsoft Windows, puede ver el progreso en dos vistas diferentes. Para controlar estas vistas, use la propiedad Desplazamiento, que incluye la configuración estándar y suave. El desplazamiento suave genera un bloque sólido de color que representa el progreso y el desplazamiento estándar aparece segmentado y se compone de una serie de bloques o rectángulos pequeños.

El control ProgressBar que se incluye con Microsoft Visual C# solo admite la configuración estándar.

En el código de ejemplo de este artículo se muestra cómo crear un control que admita las siguientes propiedades:

  • Mínimo: esta propiedad obtiene o establece el valor inferior del intervalo de valores válidos para el progreso. El valor predeterminado de esta propiedad es cero (0); no se puede establecer esta propiedad en un valor negativo.
  • Máximo: esta propiedad obtiene o establece el valor superior del intervalo de valores válidos para el progreso. El valor predeterminado de esta propiedad es 100.
  • Valor: esta propiedad obtiene o establece el nivel de progreso actual. El valor debe estar en el intervalo que definen las propiedades Minimum y Maximum.
  • ProgressBarColor: esta propiedad obtiene o establece el color de la barra de progreso.

Creación de un control ProgressBar personalizado

  1. Siga estos pasos para crear un nuevo proyecto de biblioteca de controles de Windows en Visual C#:

    1. Inicie Microsoft Visual Studio.

    2. En el menú Archivo, elija Nuevo y, a continuación, haga clic en Proyecto.

    3. En el cuadro de diálogo Nuevo proyecto, haga clic en Visual C# en Tipos de proyectoy, a continuación, haga clic en Windows Forms Biblioteca de controles en Plantillas.

    4. En el cuadro Nombre , escriba SmoothProgressBar y, a continuación, haga clic en Aceptar.

    5. En el Explorador de proyectos, cambie el nombre del módulo de clase predeterminado de UserControl1.cs a SmoothProgressBar.cs.

    6. En la ventana Propiedades del objeto UserControl, cambie la propiedad Name de UserControl1 a SmoothProgressBar.

  2. En este punto, normalmente se hereda de la clase de ese control y, a continuación, se agrega la funcionalidad adicional para ampliar un control existente. Sin embargo, la clase ProgressBar está sellada y no se puede heredar. Por lo tanto, debe compilar el control desde el principio.

    Agregue el código siguiente al archivo SmoothProgressBar.cs , en la clase derivada de UserControl.

    int min = 0;// Minimum value for progress range
    int max = 100;// Maximum value for progress range
    int val = 0;// Current progress
    Color BarColor = Color.Blue;// Color of progress meter
    
    protected override void OnResize(EventArgs e)
    {
        // Invalidate the control to get a repaint.
        this.Invalidate();
    }
    
    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        SolidBrush brush = new SolidBrush(BarColor);
        float percent = (float)(val - min) / (float)(max - min);
        Rectangle rect = this.ClientRectangle;
    
        // Calculate area for drawing the progress.
        rect.Width = (int)((float)rect.Width * percent);
    
        // Draw the progress meter.
        g.FillRectangle(brush, rect);
    
        // Draw a three-dimensional border around the control.
        Draw3DBorder(g);
    
        // Clean up.
        brush.Dispose();
        g.Dispose();
    }
    
    public int Minimum
    {
        get
        {
            return min;
        }
    
        set
        {
            // Prevent a negative value.
            if (value < 0)
            {
                value = 0;
            }
    
            // Make sure that the minimum value is never set higher than the maximum value.
            if (value > max)
            {
                max = value;
            }
    
            min = value;
    
            // Ensure value is still in range
            if (val < min)
            {
                val = min;
            }
    
            // Invalidate the control to get a repaint.
            this.Invalidate();
        }
    }
    
    public int Maximum
    {
        get
        {
            return max;
        }
    
        set
        {
            // Make sure that the maximum value is never set lower than the minimum value.
            if (value < min)
            {
                min = value;
            }
    
            max = value;
    
            // Make sure that value is still in range.
            if (val > max)
            {
                val = max;
            }
    
            // Invalidate the control to get a repaint.
            this.Invalidate();
        }
    }
    
    public int Value
    {
        get
        {
            return val;
        }
    
        set
        {
            int oldValue = val;
    
            // Make sure that the value does not stray outside the valid range.
            if (value < min)
            {
                val = min;
            }
            else if (value > max)
            {
                val = max;
            }
            else
            {
                val = value;
            }
    
            // Invalidate only the changed area.
            float percent;
    
            Rectangle newValueRect = this.ClientRectangle;
            Rectangle oldValueRect = this.ClientRectangle;
    
            // Use a new value to calculate the rectangle for progress.
            percent = (float)(val - min) / (float)(max - min);
            newValueRect.Width = (int)((float)newValueRect.Width * percent);
    
            // Use an old value to calculate the rectangle for progress.
            percent = (float)(oldValue - min) / (float)(max - min);
            oldValueRect.Width = (int)((float)oldValueRect.Width * percent);
    
            Rectangle updateRect = new Rectangle();
    
            // Find only the part of the screen that must be updated.
            if (newValueRect.Width > oldValueRect.Width)
            {
                updateRect.X = oldValueRect.Size.Width;
                updateRect.Width = newValueRect.Width - oldValueRect.Width;
            }
            else
            {
                updateRect.X = newValueRect.Size.Width;
                updateRect.Width = oldValueRect.Width - newValueRect.Width;
            }
    
            updateRect.Height = this.Height;
    
            // Invalidate the intersection region only.
            this.Invalidate(updateRect);
        }
    }
    
    public Color ProgressBarColor
    {
        get
        {
            return BarColor;
        }
    
        set
        {
            BarColor = value;
    
            // Invalidate the control to get a repaint.
            this.Invalidate();
        }
    }
    
    private void Draw3DBorder(Graphics g)
    {
        int PenWidth = (int)Pens.White.Width;
    
        g.DrawLine(Pens.DarkGray,
        new Point(this.ClientRectangle.Left, this.ClientRectangle.Top),
        new Point(this.ClientRectangle.Width - PenWidth, this.ClientRectangle.Top));
        g.DrawLine(Pens.DarkGray,
        new Point(this.ClientRectangle.Left, this.ClientRectangle.Top),
        new Point(this.ClientRectangle.Left, this.ClientRectangle.Height - PenWidth));
        g.DrawLine(Pens.White,
        new Point(this.ClientRectangle.Left, this.ClientRectangle.Height - PenWidth),
        new Point(this.ClientRectangle.Width - PenWidth, this.ClientRectangle.Height - PenWidth));
        g.DrawLine(Pens.White,
        new Point(this.ClientRectangle.Width - PenWidth, this.ClientRectangle.Top),
        new Point(this.ClientRectangle.Width - PenWidth, this.ClientRectangle.Height - PenWidth));
    }
    
  3. En el menú Compilar , haga clic en Compilar solución para compilar el proyecto.

Creación de una aplicación cliente de ejemplo

  1. En el menú Archivo, elija Nuevo y, a continuación, haga clic en Proyecto.

  2. En el cuadro de diálogo Agregar nuevo proyecto, haga clic en Visual C# en Tipos de proyecto, haga clic en Windows Forms aplicación en Plantillasy, a continuación, haga clic en Aceptar.

  3. Siga estos pasos para agregar dos instancias del control SmoothProgressBar al formulario:

    1. En el menú Herramientas , haga clic en Elegir elementos del cuadro de herramientas.

    2. Haga clic en la pestaña Componentes de .NET Framework .

    3. Haga clic en Examinary, a continuación, busque el archivo SmoothProgressBar.dll que creó en la sección Crear un control ProgressBar personalizado .

    4. Haga clic en Aceptar.

      Nota:

      El control SmoothProgressBar se agrega al cuadro de herramientas.

    5. Arrastre dos instancias del control SmoothProgressBar desde el cuadro de herramientas al formulario predeterminado del proyecto Aplicación de Windows.

  4. Arrastre un control Timer desde el cuadro de herramientas al formulario.

  5. Agregue el código siguiente al Tick evento del control Timer:

    if (this.smoothProgressBar1.Value > 0)
    {
        this.smoothProgressBar1.Value--;
        this.smoothProgressBar2.Value++;
    }
    else
    {
        this.timer1.Enabled = false;
    }
    
  6. Arrastre un control Button desde el cuadro de herramientas al formulario.

  7. Agregue el código siguiente al Click evento del control Button:

    this.smoothProgressBar1.Value = 100;
    this.smoothProgressBar2.Value = 0;
    
    this.timer1.Interval = 1;
    this.timer1.Enabled = true;
    
  8. En el menú Depurar , haga clic en Iniciar para ejecutar el proyecto de ejemplo.

  9. Haga clic en el botón .

    Nota:

    Los dos indicadores de progreso muestran el progreso del texto. Un indicador de progreso muestra el progreso de manera creciente, y el otro indicador de progreso muestra el progreso de una manera decreciente o de cuenta atrás.