Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / C# 4.0

EasyProgressBarPacket

Rate me:
Please Sign up or sign in to vote.
4.84/5 (42 votes)
18 Nov 2011CPOL4 min read 66.8K   6.9K   105  
A few progressbar examples with clone support.
using System;
using System.Drawing;
using System.ComponentModel;
using System.Drawing.Design;
using System.Drawing.Drawing2D;

namespace EasyProgressBarPacket
{
    [Editor(typeof(GradientBackgroundEditor), typeof(UITypeEditor))]
    [TypeConverter(typeof(GradientBackgroundConverter))]
    public class GradientBackground : IDisposable
    {
        #region Event

        /// <summary>
        /// Occurs when the sub properties changed of the BackgroundGradient property.
        /// </summary>
        [Description("Occurs when the sub properties changed of the BackgroundGradient property")]
        public event EventHandler GradientChanged;

        #endregion

        #region Instance Members

        private bool isBlended = false;
        private Color[] colorArray = { Color.WhiteSmoke, Color.Gainsboro };

        #endregion

        #region Constructor

        public GradientBackground() { }

        public GradientBackground(Color first, Color second)
        {
            this.colorArray[0] = first;
            this.colorArray[1] = second;
        }

        public GradientBackground(Color first, Color second, bool isBlended)
        {
            this.colorArray[0] = first;
            this.colorArray[1] = second;
            this.isBlended = isBlended;
        }

        #endregion

        #region Property

        /// <summary>
        /// Determines whether the blended effect enable or not for progress background.
        /// </summary>
        [Description("Determines whether the blended effect enable or not for progress background")]
        [RefreshProperties(RefreshProperties.Repaint)]
        [NotifyParentProperty(true)]
        [DefaultValue(false)]
        [Browsable(true)]
        public bool IsBlendedForBackground
        {
            get { return isBlended; }
            set
            {
                if (!value.Equals(isBlended))
                {
                    isBlended = value;
                    OnGradientChanged(EventArgs.Empty);
                }
            }
        }

        /// <summary>
        /// Gets or Sets, the first background color.
        /// </summary>
        [Description("Gets or Sets, the first background color")]
        [RefreshProperties(RefreshProperties.Repaint)]
        [NotifyParentProperty(true)]
        [DefaultValue(typeof(Color), "WhiteSmoke")]
        [Browsable(true)]
        public Color ColorStart
        {
            get { return colorArray[0]; }
            set
            {
                if (!value.Equals(colorArray[0]))
                {
                    colorArray[0] = value;
                    OnGradientChanged(EventArgs.Empty);
                }
            }
        }

        /// <summary>
        /// Gets or Sets, the second background color.
        /// </summary>
        [Description("Gets or Sets, the second background color")]
        [RefreshProperties(RefreshProperties.Repaint)]
        [NotifyParentProperty(true)]
        [DefaultValue(typeof(Color), "Gainsboro")]
        [Browsable(true)]
        public Color ColorEnd
        {
            get { return colorArray[1]; }
            set
            {
                if (!value.Equals(colorArray[1]))
                {
                    colorArray[1] = value;
                    OnGradientChanged(EventArgs.Empty);
                }
            }
        }

        #endregion

        #region Virtual Methods

        protected virtual void OnGradientChanged(EventArgs e)
        {
            if (GradientChanged != null)
                GradientChanged(this, e);
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion
    }

    class GradientBackgroundConverter : ExpandableObjectConverter
    {
        #region Destructor

        ~GradientBackgroundConverter()
        {
            GC.SuppressFinalize(this);
        }

        #endregion

        #region Override Methods

        //All the CanConvertTo() method needs to is check that the target type is a string.
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
                return true;
            else
                return base.CanConvertTo(context, destinationType);
        }

        //ConvertTo() simply checks that it can indeed convert to the desired type.
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
                return ToString(value);
            else
                return base.ConvertTo(context, culture, value, destinationType);
        }

        /* The exact same process occurs in reverse when converting a GradientBackground object to a string.
        First the Properties window calls CanConvertFrom(). If it returns true, the next step is to call
        the ConvertFrom() method. */
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;
            else
                return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
                return FromString(value);
            else
                return base.ConvertFrom(context, culture, value);
        }

        #endregion

        #region Helper Methods

        private string ToString(object value)
        {
            GradientBackground gradient = value as GradientBackground;    // Gelen object tipimizi GradientBackground tipine dönüştürüyoruz ve ayıklama işlemine başlıyoruz.
            ColorConverter converter = new ColorConverter();
            return String.Format("{0}, {1}, {2}",
                converter.ConvertToString(gradient.ColorStart), converter.ConvertToString(gradient.ColorEnd), gradient.IsBlendedForBackground);
        }

        private GradientBackground FromString(object value)
        {
            string[] result = ((string)value).Split(',');
            if (result.Length != 3)
                throw new ArgumentException("Could not convert to value");

            try
            {
                GradientBackground gradient = new GradientBackground();

                // Retrieve the colors
                ColorConverter converter = new ColorConverter();
                gradient.ColorStart = (Color)converter.ConvertFromString(result[0]);
                gradient.ColorEnd = (Color)converter.ConvertFromString(result[1]);
                // Retrieve the boolean value
                BooleanConverter booleanConverter = new BooleanConverter();
                gradient.IsBlendedForBackground = (bool)booleanConverter.ConvertFromString(result[2]);

                return gradient;
            }
            catch (Exception)
            {
                throw new ArgumentException("Could not convert to value");
            }
        }

        #endregion
    }

    class GradientBackgroundEditor : UITypeEditor
    {
        #region Destructor

        ~GradientBackgroundEditor()
        {
            GC.SuppressFinalize(this);
        }

        #endregion

        #region Override Methods

        public override bool GetPaintValueSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override void PaintValue(PaintValueEventArgs e)
        {
            GradientBackground gradient = e.Value as GradientBackground;
            using (LinearGradientBrush brush = new LinearGradientBrush(Point.Empty, new Point(0, e.Bounds.Height), gradient.ColorStart, gradient.ColorEnd))
            {
                if (!gradient.IsBlendedForBackground)
                    e.Graphics.FillRectangle(brush, e.Bounds);
                else
                {
                    Blend bl = new Blend(2);
                    bl.Factors = new float[] { 0.3F, 1.0F };
                    bl.Positions = new float[] { 0.0F, 1.0F };
                    brush.Blend = bl;
                    e.Graphics.FillRectangle(brush, e.Bounds);
                }
            }
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) ARELTEK
Turkey Turkey
Since 1998...

MCPD - Enterprise Application Developer

“Hesaplı hareket ettiğini zanneden ve onunla iftihar eyliyen dar kafalar; kurtulmağa, yükselmeğe elverişli hiç bir eser vücüda getirmezler. Kurtuluş ve yükselişi, ancak varlığına dayanan ve mülkü milletin gizli kapalı hazinelerini verimli hale getirmesini bilen, şahsi menfaatini millet menfaati uğruna feda eden, ruhu idealist, dimağı realist şahsiyetlerde aramalıdır.”

Nuri Demirağ, 1947

Comments and Discussions