1. #1
    AceInfinity's Avatar
    Join Date
    Feb 2012
    Location
    Canada
    Posts
    1,725

    [C#/VB.NET] AeroButton Source

    I had seen this out there somewhere, and it was all in VB.net, so after using it a couple times in VB I was impressed, but when moving over to C# I didn't have it available, so I learned everything about how this particular code worked, and converted it all over to C# from my knowledge with both languages.

    Preview:


    C# Designer Code (AeroButton.designer.cs):
    Code:
    partial class AeroButton
    {
    
    	/// <summary>
    	/// Required designer variable.
    	/// </summary>
    
    	private System.ComponentModel.IContainer components;
    	/// <summary>
    	/// Clean up any resources being used.
    	/// </summary>
    	/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    	[System.Diagnostics.DebuggerNonUserCode()]
    	protected override void Dispose(bool disposing)
    	{
    		try {
    			if (disposing) {
    				if (_imageButton != null) {
    					_imageButton.Parent.Dispose();
    					_imageButton.Parent = null;
    					_imageButton.Dispose();
    					_imageButton = null;
    				}
    				DestroyFrames();
    				if (components != null) {
    					components.Dispose();
    				}
    			}
    		} finally {
    			base.Dispose(disposing);
    		}
    	}
    
    	#region "Component Designer generated code"
    
    	/// <summary>
    	/// Required method for Designer support - do not modify 
    	/// the contents of this method with the code editor.
    	/// </summary>
    	[System.Diagnostics.DebuggerStepThrough()]
    	private void InitializeComponent()
    	{
    		this.components = new System.ComponentModel.Container();
    		this.timer = new System.Windows.Forms.Timer(this.components);
    	}
    
    	#endregion
    
    	internal System.Windows.Forms.Timer timer;
    }
    C# Source Code (AeroButton.cs):
    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Drawing.Drawing2D;
    using System.Drawing.Text;
    using PushButtonState = System.Windows.Forms.VisualStyles.PushButtonState;
    
    [ToolboxBitmap(typeof(AeroButton)), ToolboxItem(true), ToolboxItemFilter("System.Windows.Forms"), Description("Raises an event when the user clicks it.")]
    public partial class AeroButton : Button
    {
    
    	#region " Constructors "
    
    
    	public AeroButton()
    	{
    		InitializeComponent();
            timer.Interval = animationLength / framesCount;
    		base.BackColor = Color.Transparent;
    		BackColor = ColorTranslator.FromHtml("#D0D0D0");
            ForeColor = ColorTranslator.FromHtml("#505050");
            OuterBorderColor = ColorTranslator.FromHtml("#A0A0A0");
            InnerBorderColor = ColorTranslator.FromHtml("#FFFFFF");
            ShineColor = ColorTranslator.FromHtml("#FFFFFF");
            GlowColor = ColorTranslator.FromHtml("#FFFFFF");
    
    		SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true);
    		SetStyle(ControlStyles.Opaque, false);
            timer.Tick += new EventHandler(timer_Tick);
    	}
    
    	#endregion
    
    	#region " Fields and Properties "
    
    	private Color _backColor;
    
    	[DefaultValue(typeof(Color), "Black")]
    	public virtual new Color BackColor {
    		get { return _backColor; }
    		set {
    			if (!_backColor.Equals(value)) {
    				_backColor = value;
    				UseVisualStyleBackColor = false;
    				CreateFrames();
    				OnBackColorChanged(EventArgs.Empty);
    			}
    		}
    	}
    
    	[DefaultValue(typeof(Color), "White")]
    	public virtual new Color ForeColor {
    		get { return base.ForeColor; }
    		set { base.ForeColor = value; }
    	}
    
    	private Color _innerBorderColor;
    	[DefaultValue(typeof(Color), "Black"), Category("Appearance"), Description("The inner border color of the control.")]
    	public virtual Color InnerBorderColor {
    		get { return _innerBorderColor; }
    		set {
    			if (_innerBorderColor != value) {
    				_innerBorderColor = value;
    				CreateFrames();
    				if (IsHandleCreated) {
    					Invalidate();
    				}
    				OnInnerBorderColorChanged(EventArgs.Empty);
    			}
    		}
    	}
    
    	private Color _outerBorderColor;
    	[DefaultValue(typeof(Color), "White"), Category("Appearance"), Description("The outer border color of the control.")]
    	public virtual Color OuterBorderColor {
    		get { return _outerBorderColor; }
    		set {
    			if (_outerBorderColor != value) {
    				_outerBorderColor = value;
    				CreateFrames();
    				if (IsHandleCreated) {
    					Invalidate();
    				}
    				OnOuterBorderColorChanged(EventArgs.Empty);
    			}
    		}
    	}
    
    	private Color _shineColor;
    	[DefaultValue(typeof(Color), "White"), Category("Appearance"), Description("The shine color of the control.")]
    	public virtual Color ShineColor {
    		get { return _shineColor; }
    		set {
    			if (_shineColor != value) {
    				_shineColor = value;
    				CreateFrames();
    				if (IsHandleCreated) {
    					Invalidate();
    				}
    				OnShineColorChanged(EventArgs.Empty);
    			}
    		}
    	}
    
    	private Color _glowColor;
    	[DefaultValue(typeof(Color), "255,141,189,255"), Category("Appearance"), Description("The glow color of the control.")]
    	public virtual Color GlowColor {
    		get { return _glowColor; }
    		set {
    			if (_glowColor != value) {
    				_glowColor = value;
    				CreateFrames();
    				if (IsHandleCreated) {
    					Invalidate();
    				}
    				OnGlowColorChanged(EventArgs.Empty);
    			}
    		}
    	}
    
    	private bool _fadeOnFocus;
    	[DefaultValue(false), Category("Appearance"), Description("Indicates whether the button should fade in and fade out when it is getting and loosing the focus.")]
    	public virtual bool FadeOnFocus {
    		get { return _fadeOnFocus; }
    		set {
    			if (_fadeOnFocus != value) {
    				_fadeOnFocus = value;
    			}
    		}
    	}
    
    	private bool _isHovered;
    	private bool _isFocused;
    	private bool _isFocusedByKey;
    	private bool _isKeyDown;
    	private bool _isMouseDown;
    	private bool IsPressed {
    		get { return _isKeyDown || (_isMouseDown && _isHovered); }
    	}
    
    	[Browsable(false)]
    	public PushButtonState State {
    		get {
    			if (!Enabled) {
    				return PushButtonState.Disabled;
    			}
    			if (IsPressed) {
    				return PushButtonState.Pressed;
    			}
    			if (_isHovered) {
    				return PushButtonState.Hot;
    			}
    			if (_isFocused || IsDefault) {
    				return PushButtonState.Default;
    			}
    			return PushButtonState.Normal;
    		}
    	}
    
    	#endregion
    
    	#region " Events "
    	[Description("Event raised when the value of the InnerBorderColor property is changed."), Category("Property Changed")]
    	public event EventHandler InnerBorderColorChanged;
    
    	protected virtual void OnInnerBorderColorChanged(EventArgs e)
    	{
    		if (InnerBorderColorChanged != null) {
    			InnerBorderColorChanged(this, e);
    		}
    	}
    	[Description("Event raised when the value of the OuterBorderColor property is changed."), Category("Property Changed")]
    	public event EventHandler OuterBorderColorChanged;
    
    	protected virtual void OnOuterBorderColorChanged(EventArgs e)
    	{
    		if (OuterBorderColorChanged != null) {
    			OuterBorderColorChanged(this, e);
    		}
    	}
    	[Description("Event raised when the value of the ShineColor property is changed."), Category("Property Changed")]
    	public event EventHandler ShineColorChanged;
    
    	protected virtual void OnShineColorChanged(EventArgs e)
    	{
    		if (ShineColorChanged != null) {
    			ShineColorChanged(this, e);
    		}
    	}
    	[Description("Event raised when the value of the GlowColor property is changed."), Category("Property Changed")]
    	public event EventHandler GlowColorChanged;
    
    	protected virtual void OnGlowColorChanged(EventArgs e)
    	{
    		if (GlowColorChanged != null) {
    			GlowColorChanged(this, e);
    		}
    	}
    
    	#endregion
    
    	#region " Overrided Methods "
    
    	protected override void OnSizeChanged(EventArgs e)
    	{
    		CreateFrames();
    		base.OnSizeChanged(e);
    	}
    
    	protected override void OnClick(EventArgs e)
    	{
    		_isKeyDown = false;
    		_isMouseDown = false;
    		base.OnClick(e);
    	}
    
    	protected override void OnEnter(EventArgs e)
    	{
    		_isFocused = true;
    		_isFocusedByKey = true;
    		base.OnEnter(e);
    		if (_fadeOnFocus) {
    			FadeIn();
    		}
    	}
    
    	protected override void OnLeave(EventArgs e)
    	{
    		base.OnLeave(e);
    		_isFocused = false;
    		_isFocusedByKey = false;
    		_isKeyDown = false;
    		_isMouseDown = false;
    		Invalidate();
    		if (_fadeOnFocus) {
    			FadeOut();
    		}
    	}
    
    	protected override void OnKeyDown(KeyEventArgs e)
    	{
    		if (e.KeyCode == Keys.Space) {
    			_isKeyDown = true;
    			Invalidate();
    		}
    		base.OnKeyDown(e);
    	}
    
    	protected override void OnKeyUp(KeyEventArgs e)
    	{
    		if (_isKeyDown && e.KeyCode == Keys.Space) {
    			_isKeyDown = false;
    			Invalidate();
    		}
    		base.OnKeyUp(e);
    	}
    
    	protected override void OnMouseDown(MouseEventArgs e)
    	{
    		if (!_isMouseDown && e.Button == MouseButtons.Left) {
    			_isMouseDown = true;
    			_isFocusedByKey = false;
    			Invalidate();
    		}
    		base.OnMouseDown(e);
    	}
    
    	protected override void OnMouseUp(MouseEventArgs e)
    	{
    		if (_isMouseDown) {
    			_isMouseDown = false;
    			Invalidate();
    		}
    		base.OnMouseUp(e);
    	}
    
    	protected override void OnMouseMove(MouseEventArgs e)
    	{
    		base.OnMouseMove(e);
    		if (e.Button != MouseButtons.None) {
    			if (!ClientRectangle.Contains(e.X, e.Y)) {
    				if (_isHovered) {
    					_isHovered = false;
    					Invalidate();
    				}
    			} else if (!_isHovered) {
    				_isHovered = true;
    				Invalidate();
    			}
    		}
    	}
    
    	protected override void OnMouseEnter(EventArgs e)
    	{
    		_isHovered = true;
    		FadeIn();
    		Invalidate();
    		base.OnMouseEnter(e);
    	}
    
    	protected override void OnMouseLeave(EventArgs e)
    	{
    		_isHovered = false;
    		if (!(this.FadeOnFocus && _isFocusedByKey))
    			FadeOut();
    		Invalidate();
    		base.OnMouseLeave(e);
    	}
    
    	#endregion
    
    	#region " Painting "
    
    	protected override void OnPaint(PaintEventArgs e)
    	{
    		DrawButtonBackgroundFromBuffer(e.Graphics);
    		DrawForegroundFromButton(e);
    		DrawButtonForeground(e.Graphics);
    
    		if (Paint != null) {
    			Paint(this, e);
    		}
    	}
    	public new event PaintEventHandler Paint;
    
    	private void DrawButtonBackgroundFromBuffer(Graphics graphics)
    	{
    		int frame = 0;
    		if (!Enabled) {
    			frame = FRAME_DISABLED;
    		} else if (IsPressed) {
    			frame = FRAME_PRESSED;
    		} else if (!IsAnimating && _currentFrame == 0) {
    			frame = FRAME_NORMAL;
    		} else {
    			if (!HasAnimationFrames) {
    				CreateFrames(true);
    			}
    			frame = FRAME_ANIMATED + _currentFrame;
    		}
    		if (_frames == null || _frames.Count == 0) {
    			CreateFrames();
    		}
    		graphics.DrawImage(_frames[frame], Point.Empty);
    	}
    
    	private Image CreateBackgroundFrame(bool pressed, bool hovered, bool animating, bool enabled, float glowOpacity)
    	{
    		Rectangle rect = ClientRectangle;
    		if (rect.Width <= 0) {
    			rect.Width = 1;
    		}
    		if (rect.Height <= 0) {
    			rect.Height = 1;
    		}
    		Image img = new Bitmap(rect.Width, rect.Height);
    		using (Graphics g = Graphics.FromImage(img)) {
    			g.Clear(Color.Transparent);
    			DrawButtonBackground(g, rect, pressed, hovered, animating, enabled, _outerBorderColor, _backColor, _glowColor, _shineColor,
    			_innerBorderColor, glowOpacity);
    		}
    		return img;
    	}
    
    	private static void DrawButtonBackground(Graphics g, Rectangle rectangle, bool pressed, bool hovered, bool animating, bool enabled, Color outerBorderColor, Color backColor, Color glowColor, Color shineColor,
    	Color innerBorderColor, float glowOpacity)
    	{
    		SmoothingMode sm = g.SmoothingMode;
    		g.SmoothingMode = SmoothingMode.AntiAlias;
    
    		// white border
    		Rectangle rect = rectangle;
    		rect.Width -= 1;
    		rect.Height -= 1;
    		using (GraphicsPath bw = CreateRoundRectangle(rect, 4)) {
    			using (Pen p = new Pen(outerBorderColor)) {
    				g.DrawPath(p, bw);
    			}
    		}
    
    		rect.X += 1;
    		rect.Y += 1;
    		rect.Width -= 2;
    		rect.Height -= 2;
    		Rectangle rect2 = rect;
    		rect2.Height >>= 1;
    
    		// content
    		using (GraphicsPath bb = CreateRoundRectangle(rect, 2)) {
    			int opacity = If<int>(pressed, 0xcc, 0x7f);
    			using (Brush br = new SolidBrush(Color.FromArgb(opacity, backColor))) {
    				g.FillPath(br, bb);
    			}
    		}
    
    		// glow
    		if ((hovered || animating) && !pressed) {
    			using (GraphicsPath clip = CreateRoundRectangle(rect, 2)) {
    				g.SetClip(clip, CombineMode.Intersect);
    				using (GraphicsPath brad = CreateBottomRadialPath(rect)) {
    					using (PathGradientBrush pgr = new PathGradientBrush(brad)) {
    						int opacity = Convert.ToInt32(0xb2 * glowOpacity + 0.5f);
    						RectangleF bounds = brad.GetBounds();
    						pgr.CenterPoint = new PointF((bounds.Left + bounds.Right) / 2f, (bounds.Top + bounds.Bottom) / 2f);
    						pgr.CenterColor = Color.FromArgb(opacity, glowColor);
    						pgr.SurroundColors = new Color[] { Color.FromArgb(0, glowColor) };
    						g.FillPath(pgr, brad);
    					}
    				}
    				g.ResetClip();
    			}
    		}
    
    		// shine
    		if (rect2.Width > 0 && rect2.Height > 0) {
    			rect2.Height += 1;
    			using (GraphicsPath bh = CreateTopRoundRectangle(rect2, 2)) {
    				rect2.Height += 1;
    				int opacity = 0x99;
    				if (pressed | !enabled) {
    					opacity = Convert.ToInt32(0.4f * opacity + 0.5f);
    				}
    				using (LinearGradientBrush br = new LinearGradientBrush(rect2, Color.FromArgb(opacity, shineColor), Color.FromArgb(opacity / 3, shineColor), LinearGradientMode.Vertical)) {
    					g.FillPath(br, bh);
    				}
    			}
    			rect2.Height -= 2;
    		}
    
    		// black border
    		using (GraphicsPath bb = CreateRoundRectangle(rect, 3)) {
    			using (Pen p = new Pen(innerBorderColor)) {
    				g.DrawPath(p, bb);
    			}
    		}
    
    		g.SmoothingMode = sm;
    	}
    
    	private void DrawButtonForeground(Graphics g)
    	{
    		if (Focused && ShowFocusCues) {
    			// && isFocusedByKey 
    			Rectangle rect = ClientRectangle;
    			rect.Inflate(-4, -4);
    			ControlPaint.DrawFocusRectangle(g, rect);
    		}
    	}
    
    	private Button _imageButton;
    	private void DrawForegroundFromButton(PaintEventArgs pevent)
    	{
    		if (_imageButton == null) {
    			_imageButton = new Button();
    			_imageButton.Parent = new TransparentControl();
    			_imageButton.SuspendLayout();
    			_imageButton.BackColor = Color.Transparent;
    			_imageButton.FlatAppearance.BorderSize = 0;
    			_imageButton.FlatStyle = FlatStyle.Flat;
    		} else {
    			_imageButton.SuspendLayout();
    		}
    		_imageButton.AutoEllipsis = AutoEllipsis;
    		if (Enabled) {
    			_imageButton.ForeColor = ForeColor;
    		} else {
    			_imageButton.ForeColor = Color.FromArgb((3 * ForeColor.R + _backColor.R) >> 2, (3 * ForeColor.G + _backColor.G) >> 2, (3 * ForeColor.B + _backColor.B) >> 2);
    		}
    		_imageButton.Font = Font;
    		_imageButton.RightToLeft = RightToLeft;
    		_imageButton.Image = Image;
    		if (Image != null && !Enabled) {
    			Size size = Image.Size;
    			float[][] newColorMatrix = new float[5][];
    			newColorMatrix[0] = new float[] {
    				0.2125f,
    				0.2125f,
    				0.2125f,
    				0f,
    				0f
    			};
    			newColorMatrix[1] = new float[] {
    				0.2577f,
    				0.2577f,
    				0.2577f,
    				0f,
    				0f
    			};
    			newColorMatrix[2] = new float[] {
    				0.0361f,
    				0.0361f,
    				0.0361f,
    				0f,
    				0f
    			};
    			float[] arr = new float[5];
    			arr[3] = 1f;
    			newColorMatrix[3] = arr;
    			newColorMatrix[4] = new float[] {
    				0.38f,
    				0.38f,
    				0.38f,
    				0f,
    				1f
    			};
    			System.Drawing.Imaging.ColorMatrix matrix = new System.Drawing.Imaging.ColorMatrix(newColorMatrix);
    			System.Drawing.Imaging.ImageAttributes disabledImageAttr = new System.Drawing.Imaging.ImageAttributes();
    			disabledImageAttr.ClearColorKey();
    			disabledImageAttr.SetColorMatrix(matrix);
    			_imageButton.Image = new Bitmap(Image.Width, Image.Height);
    			using (Graphics gr = Graphics.FromImage(_imageButton.Image)) {
    				gr.DrawImage(Image, new Rectangle(0, 0, size.Width, size.Height), 0, 0, size.Width, size.Height, GraphicsUnit.Pixel, disabledImageAttr);
    			}
    		}
    		_imageButton.ImageAlign = ImageAlign;
    		_imageButton.ImageIndex = ImageIndex;
    		_imageButton.ImageKey = ImageKey;
    		_imageButton.ImageList = ImageList;
    		_imageButton.Padding = Padding;
    		_imageButton.Size = Size;
    		_imageButton.Text = Text;
    		_imageButton.TextAlign = TextAlign;
    		_imageButton.TextImageRelation = TextImageRelation;
    		_imageButton.UseCompatibleTextRendering = UseCompatibleTextRendering;
    		_imageButton.UseMnemonic = UseMnemonic;
    		_imageButton.ResumeLayout();
    		InvokePaint(_imageButton, pevent);
    		if (_imageButton.Image != null && !object.ReferenceEquals(_imageButton.Image, Image)) {
    			_imageButton.Image.Dispose();
    			_imageButton.Image = null;
    		}
    	}
    
    	private class TransparentControl : Control
    	{
    		protected override void OnPaintBackground(PaintEventArgs pevent)
    		{
    		}
    		protected override void OnPaint(PaintEventArgs e)
    		{
    		}
    	}
    
    	private static GraphicsPath CreateRoundRectangle(Rectangle rectangle, int radius)
    	{
    		GraphicsPath path = new GraphicsPath();
    		int l = rectangle.Left;
    		int t = rectangle.Top;
    		int w = rectangle.Width;
    		int h = rectangle.Height;
    		int d = radius << 1;
    		path.AddArc(l, t, d, d, 180, 90);
    		// topleft
    		path.AddLine(l + radius, t, l + w - radius, t);
    		// top
    		path.AddArc(l + w - d, t, d, d, 270, 90);
    		// topright
    		path.AddLine(l + w, t + radius, l + w, t + h - radius);
    		// right
    		path.AddArc(l + w - d, t + h - d, d, d, 0, 90);
    		// bottomright
    		path.AddLine(l + w - radius, t + h, l + radius, t + h);
    		// bottom
    		path.AddArc(l, t + h - d, d, d, 90, 90);
    		// bottomleft
    		path.AddLine(l, t + h - radius, l, t + radius);
    		// left
    		path.CloseFigure();
    		return path;
    	}
    
    	private static GraphicsPath CreateTopRoundRectangle(Rectangle rectangle, int radius)
    	{
    		GraphicsPath path = new GraphicsPath();
    		int l = rectangle.Left;
    		int t = rectangle.Top;
    		int w = rectangle.Width;
    		int h = rectangle.Height;
    		int d = radius << 1;
    		path.AddArc(l, t, d, d, 180, 90);
    		// topleft
    		path.AddLine(l + radius, t, l + w - radius, t);
    		// top
    		path.AddArc(l + w - d, t, d, d, 270, 90);
    		// topright
    		path.AddLine(l + w, t + radius, l + w, t + h);
    		// right
    		path.AddLine(l + w, t + h, l, t + h);
    		// bottom
    		path.AddLine(l, t + h, l, t + radius);
    		// left
    		path.CloseFigure();
    		return path;
    	}
    
    	private static GraphicsPath CreateBottomRadialPath(Rectangle rectangle)
    	{
    		GraphicsPath path = new GraphicsPath();
    		RectangleF rect = rectangle;
    		rect.X -= rect.Width * 0.35f;
    		rect.Y -= rect.Height * 0.15f;
    		rect.Width *= 1.7f;
    		rect.Height *= 2.3f;
    		path.AddEllipse(rect);
    		path.CloseFigure();
    		return path;
    	}
    
    	#endregion
    
    	#region " Unused Properties & Events "
    
    	[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)]
    	public new FlatButtonAppearance FlatAppearance {
    		get { return base.FlatAppearance; }
    	}
    
    	[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)]
    	public new FlatStyle FlatStyle {
    		get { return base.FlatStyle; }
    		set { base.FlatStyle = value; }
    	}
    
    	[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)]
    	public new bool UseVisualStyleBackColor {
    		get { return base.UseVisualStyleBackColor; }
    		set { base.UseVisualStyleBackColor = value; }
    	}
    
    	#endregion
    
    	#region " Animation Support "
    
    
    	private List<Image> _frames;
    	private const int FRAME_DISABLED = 0;
    	private const int FRAME_PRESSED = 1;
    	private const int FRAME_NORMAL = 2;
    
    	private const int FRAME_ANIMATED = 3;
    	private bool HasAnimationFrames {
    		get { return _frames != null && _frames.Count > FRAME_ANIMATED; }
    	}
    
    	private void CreateFrames()
    	{
    		CreateFrames(false);
    	}
    
    	private void CreateFrames(bool withAnimationFrames)
    	{
    		DestroyFrames();
    		if (!IsHandleCreated) {
    			return;
    		}
    		if (_frames == null) {
    			_frames = new List<Image>();
    		}
    		_frames.Add(CreateBackgroundFrame(false, false, false, false, 0));
    		_frames.Add(CreateBackgroundFrame(true, true, false, true, 0));
    		_frames.Add(CreateBackgroundFrame(false, false, false, true, 0));
    		if (!withAnimationFrames) {
    			return;
    		}
    		for (int i = 0; i <= framesCount - 1; i++) {
    			_frames.Add(CreateBackgroundFrame(false, true, true, true, Convert.ToSingle(i) / (framesCount - 1f)));
    		}
    	}
    
    	private void DestroyFrames()
    	{
    		if (_frames != null) {
    			while (_frames.Count > 0) {
    				_frames[_frames.Count - 1].Dispose();
    				_frames.RemoveAt(_frames.Count - 1);
    			}
    		}
    	}
    
    	private const int animationLength = 300;
    	private const int framesCount = 10;
    	private int _currentFrame;
    
    	private int _direction;
    	private bool IsAnimating {
    		get { return _direction != 0; }
    	}
    
    	private void FadeIn()
    	{
    		_direction = 1;
    		timer.Enabled = true;
    	}
    
    	private void FadeOut()
    	{
    		_direction = -1;
            timer.Enabled = true;
    	}
    
    	private void timer_Tick(object sender, EventArgs e)
    	{
            if (!timer.Enabled)
            {
    			return;
    		}
    		Refresh();
    		_currentFrame += _direction;
    		if (_currentFrame == -1) {
    			_currentFrame = 0;
                timer.Enabled = false;
    			_direction = 0;
    			return;
    		}
    		if (_currentFrame == framesCount) {
    			_currentFrame = framesCount - 1;
                timer.Enabled = false;
    			_direction = 0;
    		}
    	}
    
    	#endregion
    
    	#region " Misc "
    	private static T If<T>(bool condition, T obj1, T obj2)
    	{
    		if (condition)
    			return obj1;
    		return obj2;
    	}
    	#endregion
    
    }
    Last edited by AceInfinity; 05-07-2012 at 09:18 PM.
    Automation Programmer
    Microsoft MVP [2012 - 2018]


    • Ad Bot

      advertising
      Beep.

        
       

  2. #2
    AceInfinity's Avatar
    Join Date
    Feb 2012
    Location
    Canada
    Posts
    1,725

    Re: [C#/VB.NET] AeroButton Source

    VB.NET Designer Code (AeroButton.designer.cs):
    Code:
    Partial Class AeroButton
    
        ''' <summary>
        ''' Required designer variable.
        ''' </summary>
        Private components As System.ComponentModel.IContainer
    
        ''' <summary>
        ''' Clean up any resources being used.
        ''' </summary>
        ''' <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        <System.Diagnostics.DebuggerNonUserCode()> _
        Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            Try
                If disposing Then
                    If _imageButton IsNot Nothing Then
                        _imageButton.Parent.Dispose()
                        _imageButton.Parent = Nothing
                        _imageButton.Dispose()
                        _imageButton = Nothing
                    End If
                    DestroyFrames()
                    If components IsNot Nothing Then
                        components.Dispose()
                    End If
                End If
            Finally
                MyBase.Dispose(disposing)
            End Try
        End Sub
    
    #Region "Component Designer generated code"
    
        ''' <summary>
        ''' Required method for Designer support - do not modify 
        ''' the contents of this method with the code editor.
        ''' </summary>
        <System.Diagnostics.DebuggerStepThrough()> _
        Private Sub InitializeComponent()
            Me.components = New System.ComponentModel.Container()
            Me.timer = New System.Windows.Forms.Timer(Me.components)
        End Sub
    
    #End Region
    
        Friend WithEvents timer As System.Windows.Forms.Timer
    
    End Class
    VB.NET Source Code (AeroButton.cs):
    Code:
    Imports System
    Imports System.Collections.Generic
    Imports System.ComponentModel
    Imports System.Data
    Imports System.Drawing
    Imports System.Text
    Imports System.Windows.Forms
    Imports System.Drawing.Drawing2D
    Imports System.Drawing.Text
    Imports PushButtonState = System.Windows.Forms.VisualStyles.PushButtonState
    
    <ToolboxBitmap(GetType(AeroButton)), ToolboxItem(True), ToolboxItemFilter("System.Windows.Forms"), Description("Raises an event when the user clicks it.")> _
    Partial Public Class AeroButton
        Inherits Button
    
    #Region " Constructors "
    
    
        Public Sub New()
            InitializeComponent()
            Timer.Interval = animationLength \ framesCount
            MyBase.BackColor = Color.Transparent
            BackColor = Color.Black
            ForeColor = Color.White
            OuterBorderColor = Color.White
            InnerBorderColor = Color.Black
            ShineColor = Color.White
            GlowColor = Color.FromArgb(-7488001) 'unchecked((int)(0xFF8DBDFF)));
            SetStyle(ControlStyles.SupportsTransparentBackColor, True)
            SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.OptimizedDoubleBuffer Or ControlStyles.ResizeRedraw Or ControlStyles.SupportsTransparentBackColor Or ControlStyles.UserPaint, True)
            SetStyle(ControlStyles.Opaque, False)
        End Sub
    
    #End Region
    
    #Region " Fields and Properties "
    
        Private _backColor As Color
            
        <DefaultValue(GetType(Color), "Black")> _
        Public Overridable Shadows Property BackColor() As Color
            Get
                Return _backColor
            End Get
            Set(ByVal value As Color)
                If Not _backColor.Equals(value) Then
                    _backColor = value
                    UseVisualStyleBackColor = False
                    CreateFrames()
                    OnBackColorChanged(EventArgs.Empty)
                End If
            End Set
        End Property
    
        <DefaultValue(GetType(Color), "White")> _
        Public Overridable Shadows Property ForeColor() As Color
            Get
                Return MyBase.ForeColor
            End Get
            Set(ByVal value As Color)
                MyBase.ForeColor = value
            End Set
        End Property
    
        Private _innerBorderColor As Color
        <DefaultValue(GetType(Color), "Black"), Category("Appearance"), Description("The inner border color of the control.")> _
        Public Overridable Property InnerBorderColor() As Color
            Get
                Return _innerBorderColor
            End Get
            Set(ByVal value As Color)
                If _innerBorderColor <> value Then
                    _innerBorderColor = value
                    CreateFrames()
                    If IsHandleCreated Then
                        Invalidate()
                    End If
                    OnInnerBorderColorChanged(EventArgs.Empty)
                End If
            End Set
        End Property
    
        Private _outerBorderColor As Color
        <DefaultValue(GetType(Color), "White"), Category("Appearance"), Description("The outer border color of the control.")> _
        Public Overridable Property OuterBorderColor() As Color
            Get
                Return _outerBorderColor
            End Get
            Set(ByVal value As Color)
                If _outerBorderColor <> value Then
                    _outerBorderColor = value
                    CreateFrames()
                    If IsHandleCreated Then
                        Invalidate()
                    End If
                    OnOuterBorderColorChanged(EventArgs.Empty)
                End If
            End Set
        End Property
    
        Private _shineColor As Color
        <DefaultValue(GetType(Color), "White"), Category("Appearance"), Description("The shine color of the control.")> _
        Public Overridable Property ShineColor() As Color
            Get
                Return _shineColor
            End Get
            Set(ByVal value As Color)
                If _shineColor <> value Then
                    _shineColor = value
                    CreateFrames()
                    If IsHandleCreated Then
                        Invalidate()
                    End If
                    OnShineColorChanged(EventArgs.Empty)
                End If
            End Set
        End Property
    
        Private _glowColor As Color
        <DefaultValue(GetType(Color), "255,141,189,255"), Category("Appearance"), Description("The glow color of the control.")> _
        Public Overridable Property GlowColor() As Color
            Get
                Return _glowColor
            End Get
            Set(ByVal value As Color)
                If _glowColor <> value Then
                    _glowColor = value
                    CreateFrames()
                    If IsHandleCreated Then
                        Invalidate()
                    End If
                    OnGlowColorChanged(EventArgs.Empty)
                End If
            End Set
        End Property
    
        Private _fadeOnFocus As Boolean
        <DefaultValue(False), Category("Appearance"), Description("Indicates whether the button should fade in and fade out when it is getting and loosing the focus.")> _
        Public Overridable Property FadeOnFocus() As Boolean
            Get
                Return _fadeOnFocus
            End Get
            Set(ByVal value As Boolean)
                If _fadeOnFocus <> value Then
                    _fadeOnFocus = value
                End If
            End Set
        End Property
    
        Private _isHovered As Boolean
        Private _isFocused As Boolean
        Private _isFocusedByKey As Boolean
        Private _isKeyDown As Boolean
        Private _isMouseDown As Boolean
        Private ReadOnly Property IsPressed() As Boolean
            Get
                Return _isKeyDown OrElse (_isMouseDown AndAlso _isHovered)
            End Get
        End Property
    
        <Browsable(False)> _
        Public ReadOnly Property State() As PushButtonState
            Get
                If Not Enabled Then
                    Return PushButtonState.Disabled
                End If
                If IsPressed Then
                    Return PushButtonState.Pressed
                End If
                If _isHovered Then
                    Return PushButtonState.Hot
                End If
                If _isFocused OrElse IsDefault Then
                    Return PushButtonState.Default
                End If
                Return PushButtonState.Normal
            End Get
        End Property
    
    #End Region
    
    #Region " Events "
    <Description("Event raised when the value of the InnerBorderColor property is changed."), Category("Property Changed")> _
        Public Event InnerBorderColorChanged As EventHandler
    
        Protected Overridable Sub OnInnerBorderColorChanged(ByVal e As EventArgs)
            RaiseEvent InnerBorderColorChanged(Me, e)
        End Sub
    <Description("Event raised when the value of the OuterBorderColor property is changed."), Category("Property Changed")> _
        Public Event OuterBorderColorChanged As EventHandler
    
        Protected Overridable Sub OnOuterBorderColorChanged(ByVal e As EventArgs)
            RaiseEvent OuterBorderColorChanged(Me, e)
        End Sub
    <Description("Event raised when the value of the ShineColor property is changed."), Category("Property Changed")> _
        Public Event ShineColorChanged As EventHandler
    
        Protected Overridable Sub OnShineColorChanged(ByVal e As EventArgs)
            RaiseEvent ShineColorChanged(Me, e)
        End Sub
    <Description("Event raised when the value of the GlowColor property is changed."), Category("Property Changed")> _
        Public Event GlowColorChanged As EventHandler
    
        Protected Overridable Sub OnGlowColorChanged(ByVal e As EventArgs)
            RaiseEvent GlowColorChanged(Me, e)
        End Sub
    
    #End Region
    
    #Region " Overrided Methods "
        Protected Overloads Overrides Sub OnSizeChanged(ByVal e As EventArgs)
            CreateFrames()
            MyBase.OnSizeChanged(e)
        End Sub
    
        Protected Overloads Overrides Sub OnClick(ByVal e As EventArgs)
            _isKeyDown = False
            _isMouseDown = False
            MyBase.OnClick(e)
        End Sub
    
        Protected Overloads Overrides Sub OnEnter(ByVal e As EventArgs)
            _isFocused = True
            _isFocusedByKey = True
            MyBase.OnEnter(e)
            If _fadeOnFocus Then
                FadeIn()
            End If
        End Sub
    
        Protected Overloads Overrides Sub OnLeave(ByVal e As EventArgs)
            MyBase.OnLeave(e)
            _isFocused = False
            _isFocusedByKey = False
            _isKeyDown = False
            _isMouseDown = False
            Invalidate()
            If _fadeOnFocus Then
                FadeOut()
            End If
        End Sub
    
        Protected Overloads Overrides Sub OnKeyDown(ByVal e As KeyEventArgs)
            If e.KeyCode = Keys.Space Then
                _isKeyDown = True
                Invalidate()
            End If
            MyBase.OnKeyDown(e)
        End Sub
    
        Protected Overloads Overrides Sub OnKeyUp(ByVal e As KeyEventArgs)
            If _isKeyDown AndAlso e.KeyCode = Keys.Space Then
                _isKeyDown = False
                Invalidate()
            End If
            MyBase.OnKeyUp(e)
        End Sub
    
        Protected Overloads Overrides Sub OnMouseDown(ByVal e As MouseEventArgs)
            If Not _isMouseDown AndAlso e.Button = MouseButtons.Left Then
                _isMouseDown = True
                _isFocusedByKey = False
                Invalidate()
            End If
            MyBase.OnMouseDown(e)
        End Sub
    
        Protected Overloads Overrides Sub OnMouseUp(ByVal e As MouseEventArgs)
            If _isMouseDown Then
                _isMouseDown = False
                Invalidate()
            End If
            MyBase.OnMouseUp(e)
        End Sub
    
        Protected Overloads Overrides Sub OnMouseMove(ByVal e As MouseEventArgs)
            MyBase.OnMouseMove(e)
            If e.Button <> MouseButtons.None Then
                If Not ClientRectangle.Contains(e.X, e.Y) Then
                    If _isHovered Then
                        _isHovered = False
                        Invalidate()
                    End If
                ElseIf Not _isHovered Then
                    _isHovered = True
                    Invalidate()
                End If
            End If
        End Sub
    
        Protected Overloads Overrides Sub OnMouseEnter(ByVal e As EventArgs)
            _isHovered = True
            FadeIn()
            Invalidate()
            MyBase.OnMouseEnter(e)
        End Sub
    
        Protected Overloads Overrides Sub OnMouseLeave(ByVal e As EventArgs)
            _isHovered = False
            If Not (Me.FadeOnFocus AndAlso _isFocusedByKey) Then FadeOut()
            Invalidate()
            MyBase.OnMouseLeave(e)
        End Sub
    
    #End Region
    
    #Region " Painting "
    
        Protected Overloads Overrides Sub OnPaint(ByVal e As PaintEventArgs)
            DrawButtonBackgroundFromBuffer(e.Graphics)
            DrawForegroundFromButton(e)
            DrawButtonForeground(e.Graphics)
    
            RaiseEvent Paint(Me, e)
        End Sub
    Public Shadows Event Paint As PaintEventHandler
    
        Private Sub DrawButtonBackgroundFromBuffer(ByVal graphics As Graphics)
            Dim frame As Integer
            If Not Enabled Then
                frame = FRAME_DISABLED
            ElseIf IsPressed Then
                frame = FRAME_PRESSED
            ElseIf Not IsAnimating AndAlso _currentFrame = 0 Then
                frame = FRAME_NORMAL
            Else
                If Not HasAnimationFrames Then
                    CreateFrames(True)
                End If
                frame = FRAME_ANIMATED + _currentFrame
            End If
            If _frames Is Nothing OrElse _frames.Count = 0 Then
                CreateFrames()
            End If
            graphics.DrawImage(_frames(frame), Point.Empty)
        End Sub
    
        Private Function CreateBackgroundFrame(ByVal pressed As Boolean, ByVal hovered As Boolean, ByVal animating As Boolean, ByVal enabled As Boolean, ByVal glowOpacity As Single) As Image
            Dim rect As Rectangle = ClientRectangle
            If rect.Width <= 0 Then
                rect.Width = 1
            End If
            If rect.Height <= 0 Then
                rect.Height = 1
            End If
            Dim img As Image = New Bitmap(rect.Width, rect.Height)
            Using g As Graphics = Graphics.FromImage(img)
                g.Clear(Color.Transparent)
                DrawButtonBackground(g, rect, pressed, hovered, animating, enabled, _
                _outerBorderColor, _backColor, _glowColor, _shineColor, _innerBorderColor, glowOpacity)
            End Using
            Return img
        End Function
    
        Private Shared Sub DrawButtonBackground(ByVal g As Graphics, ByVal rectangle As Rectangle, ByVal pressed As Boolean, ByVal hovered As Boolean, ByVal animating As Boolean, ByVal enabled As Boolean, _
        ByVal outerBorderColor As Color, ByVal backColor As Color, ByVal glowColor As Color, ByVal shineColor As Color, ByVal innerBorderColor As Color, ByVal glowOpacity As Single)
            Dim sm As SmoothingMode = g.SmoothingMode
            g.SmoothingMode = SmoothingMode.AntiAlias
    
            ' white border
            Dim rect As Rectangle = rectangle
            rect.Width -= 1
            rect.Height -= 1
            Using bw As GraphicsPath = CreateRoundRectangle(rect, 4)
                Using p As New Pen(outerBorderColor)
                    g.DrawPath(p, bw)
                End Using
            End Using
    
            rect.X += 1
            rect.Y += 1
            rect.Width -= 2
            rect.Height -= 2
            Dim rect2 As Rectangle = rect
            rect2.Height >>= 1
    
            ' content
            Using bb As GraphicsPath = CreateRoundRectangle(rect, 2)
                Dim opacity As Integer = [If](Of Integer)(pressed, &HCC, &H7F)
                Using br As Brush = New SolidBrush(Color.FromArgb(opacity, backColor))
                    g.FillPath(br, bb)
                End Using
            End Using
    
            ' glow
            If (hovered OrElse animating) AndAlso Not pressed Then
                Using clip As GraphicsPath = CreateRoundRectangle(rect, 2)
                    g.SetClip(clip, CombineMode.Intersect)
                    Using brad As GraphicsPath = CreateBottomRadialPath(rect)
                        Using pgr As New PathGradientBrush(brad)
                            Dim opacity As Integer = Convert.ToInt32(&HB2 * glowOpacity + 0.5F)
                            Dim bounds As RectangleF = brad.GetBounds()
                            pgr.CenterPoint = New PointF((bounds.Left + bounds.Right) / 2.0F, (bounds.Top + bounds.Bottom) / 2.0F)
                            pgr.CenterColor = Color.FromArgb(opacity, glowColor)
                            pgr.SurroundColors = New Color() {Color.FromArgb(0, glowColor)}
                            g.FillPath(pgr, brad)
                        End Using
                    End Using
                    g.ResetClip()
                End Using
            End If
    
            ' shine
            If rect2.Width > 0 AndAlso rect2.Height > 0 Then
                rect2.Height += 1
                Using bh As GraphicsPath = CreateTopRoundRectangle(rect2, 2)
                    rect2.Height += 1
                    Dim opacity As Integer = &H99
                    If pressed Or Not enabled Then
                        opacity = Convert.ToInt32(0.4F * opacity + 0.5F)
                    End If
                    Using br As New LinearGradientBrush(rect2, Color.FromArgb(opacity, shineColor), Color.FromArgb(opacity \ 3, shineColor), LinearGradientMode.Vertical)
                        g.FillPath(br, bh)
                    End Using
                End Using
                rect2.Height -= 2
            End If
    
            ' black border
            Using bb As GraphicsPath = CreateRoundRectangle(rect, 3)
                Using p As New Pen(innerBorderColor)
                    g.DrawPath(p, bb)
                End Using
            End Using
    
            g.SmoothingMode = sm
        End Sub
    
        Private Sub DrawButtonForeground(ByVal g As Graphics)
            If Focused AndAlso ShowFocusCues Then
                ' && isFocusedByKey 
                Dim rect As Rectangle = ClientRectangle
                rect.Inflate(-4, -4)
                ControlPaint.DrawFocusRectangle(g, rect)
            End If
        End Sub
    
        Private _imageButton As Button
        Private Sub DrawForegroundFromButton(ByVal pevent As PaintEventArgs)
            If _imageButton Is Nothing Then
                _imageButton = New Button()
                _imageButton.Parent = New TransparentControl()
                _imageButton.SuspendLayout()
                _imageButton.BackColor = Color.Transparent
                _imageButton.FlatAppearance.BorderSize = 0
                _imageButton.FlatStyle = FlatStyle.Flat
            Else
                _imageButton.SuspendLayout()
            End If
            _imageButton.AutoEllipsis = AutoEllipsis
            If Enabled Then
                _imageButton.ForeColor = ForeColor
            Else
                _imageButton.ForeColor = Color.FromArgb((3 * ForeColor.R + _backColor.R) >> 2, (3 * ForeColor.G + _backColor.G) >> 2, (3 * ForeColor.B + _backColor.B) >> 2)
            End If
            _imageButton.Font = Font
            _imageButton.RightToLeft = RightToLeft
            _imageButton.Image = Image
            If Image IsNot Nothing AndAlso Not Enabled Then
                Dim size As Size = Image.Size
                Dim newColorMatrix As Single()() = New Single(4)() {}
                newColorMatrix(0) = New Single() {0.2125F, 0.2125F, 0.2125F, 0.0F, 0.0F}
                newColorMatrix(1) = New Single() {0.2577F, 0.2577F, 0.2577F, 0.0F, 0.0F}
                newColorMatrix(2) = New Single() {0.0361F, 0.0361F, 0.0361F, 0.0F, 0.0F}
                Dim arr As Single() = New Single(4) {}
                arr(3) = 1.0F
                newColorMatrix(3) = arr
                newColorMatrix(4) = New Single() {0.38F, 0.38F, 0.38F, 0.0F, 1.0F}
                Dim matrix As New System.Drawing.Imaging.ColorMatrix(newColorMatrix)
                Dim disabledImageAttr As New System.Drawing.Imaging.ImageAttributes()
                disabledImageAttr.ClearColorKey()
                disabledImageAttr.SetColorMatrix(matrix)
                _imageButton.Image = New Bitmap(Image.Width, Image.Height)
                Using gr As Graphics = Graphics.FromImage(_imageButton.Image)
                    gr.DrawImage(Image, New Rectangle(0, 0, size.Width, size.Height), 0, 0, size.Width, size.Height, GraphicsUnit.Pixel, disabledImageAttr)
                End Using
            End If
            _imageButton.ImageAlign = ImageAlign
            _imageButton.ImageIndex = ImageIndex
            _imageButton.ImageKey = ImageKey
            _imageButton.ImageList = ImageList
            _imageButton.Padding = Padding
            _imageButton.Size = Size
            _imageButton.Text = Text
            _imageButton.TextAlign = TextAlign
            _imageButton.TextImageRelation = TextImageRelation
            _imageButton.UseCompatibleTextRendering = UseCompatibleTextRendering
            _imageButton.UseMnemonic = UseMnemonic
            _imageButton.ResumeLayout()
            InvokePaint(_imageButton, pevent)
            If _imageButton.Image IsNot Nothing AndAlso _imageButton.Image IsNot Image Then
                _imageButton.Image.Dispose()
                _imageButton.Image = Nothing
            End If
        End Sub
    
        Private Class TransparentControl
            Inherits Control
            Protected Overloads Overrides Sub OnPaintBackground(ByVal pevent As PaintEventArgs)
            End Sub
            Protected Overloads Overrides Sub OnPaint(ByVal e As PaintEventArgs)
            End Sub
        End Class
    
        Private Shared Function CreateRoundRectangle(ByVal rectangle As Rectangle, ByVal radius As Integer) As GraphicsPath
            Dim path As New GraphicsPath()
            Dim l As Integer = rectangle.Left
            Dim t As Integer = rectangle.Top
            Dim w As Integer = rectangle.Width
            Dim h As Integer = rectangle.Height
            Dim d As Integer = radius << 1
            path.AddArc(l, t, d, d, 180, 90) ' topleft
            path.AddLine(l + radius, t, l + w - radius, t) ' top
            path.AddArc(l + w - d, t, d, d, 270, 90) ' topright
            path.AddLine(l + w, t + radius, l + w, t + h - radius) ' right
            path.AddArc(l + w - d, t + h - d, d, d, 0, 90) ' bottomright
            path.AddLine(l + w - radius, t + h, l + radius, t + h) ' bottom
            path.AddArc(l, t + h - d, d, d, 90, 90) ' bottomleft
            path.AddLine(l, t + h - radius, l, t + radius) ' left
            path.CloseFigure()
            Return path
        End Function
    
        Private Shared Function CreateTopRoundRectangle(ByVal rectangle As Rectangle, ByVal radius As Integer) As GraphicsPath
            Dim path As New GraphicsPath()
            Dim l As Integer = rectangle.Left
            Dim t As Integer = rectangle.Top
            Dim w As Integer = rectangle.Width
            Dim h As Integer = rectangle.Height
            Dim d As Integer = radius << 1
            path.AddArc(l, t, d, d, 180, 90) ' topleft
            path.AddLine(l + radius, t, l + w - radius, t) ' top
            path.AddArc(l + w - d, t, d, d, 270, 90) ' topright
            path.AddLine(l + w, t + radius, l + w, t + h) ' right
            path.AddLine(l + w, t + h, l, t + h) ' bottom
            path.AddLine(l, t + h, l, t + radius) ' left
            path.CloseFigure()
            Return path
        End Function
    
        Private Shared Function CreateBottomRadialPath(ByVal rectangle As Rectangle) As GraphicsPath
            Dim path As New GraphicsPath()
            Dim rect As RectangleF = rectangle
            rect.X -= rect.Width * 0.35F
            rect.Y -= rect.Height * 0.15F
            rect.Width *= 1.7F
            rect.Height *= 2.3F
            path.AddEllipse(rect)
            path.CloseFigure()
            Return path
        End Function
    
    #End Region
    
    #Region " Unused Properties & Events "
    
        <Browsable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)> _
        Public Shadows ReadOnly Property FlatAppearance() As FlatButtonAppearance
            Get
                Return MyBase.FlatAppearance
            End Get
        End Property
    
        <Browsable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)> _
        Public Shadows Property FlatStyle() As FlatStyle
            Get
                Return MyBase.FlatStyle
            End Get
            Set(ByVal value As FlatStyle)
                MyBase.FlatStyle = value
            End Set
        End Property
    
        <Browsable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never)> _
        Public Shadows Property UseVisualStyleBackColor() As Boolean
            Get
                Return MyBase.UseVisualStyleBackColor
            End Get
            Set(ByVal value As Boolean)
                MyBase.UseVisualStyleBackColor = value
            End Set
        End Property
    
    #End Region
    
    #Region " Animation Support "
    
        Private _frames As List(Of Image)
    
        Private Const FRAME_DISABLED As Integer = 0
        Private Const FRAME_PRESSED As Integer = 1
        Private Const FRAME_NORMAL As Integer = 2
        Private Const FRAME_ANIMATED As Integer = 3
    
        Private ReadOnly Property HasAnimationFrames() As Boolean
            Get
                Return _frames IsNot Nothing AndAlso _frames.Count > FRAME_ANIMATED
            End Get
        End Property
    
        Private Sub CreateFrames()
            CreateFrames(False)
        End Sub
    
        Private Sub CreateFrames(ByVal withAnimationFrames As Boolean)
            DestroyFrames()
            If Not IsHandleCreated Then
                Return
            End If
            If _frames Is Nothing Then
                _frames = New List(Of Image)()
            End If
            _frames.Add(CreateBackgroundFrame(False, False, False, False, 0))
            _frames.Add(CreateBackgroundFrame(True, True, False, True, 0))
            _frames.Add(CreateBackgroundFrame(False, False, False, True, 0))
            If Not withAnimationFrames Then
                Return
            End If
            For i As Integer = 0 To framesCount - 1
                _frames.Add(CreateBackgroundFrame(False, True, True, True, Convert.ToSingle(i) / (framesCount - 1.0F)))
            Next
        End Sub
    
        Private Sub DestroyFrames()
            If _frames IsNot Nothing Then
                While _frames.Count > 0
                    _frames(_frames.Count - 1).Dispose()
                    _frames.RemoveAt(_frames.Count - 1)
                End While
            End If
        End Sub
    
        Private Const animationLength As Integer = 300
        Private Const framesCount As Integer = 10
        Private _currentFrame As Integer
        Private _direction As Integer
    
        Private ReadOnly Property IsAnimating() As Boolean
            Get
                Return _direction <> 0
            End Get
        End Property
    
        Private Sub FadeIn()
            _direction = 1
            Timer.Enabled = True
        End Sub
    
        Private Sub FadeOut()
            _direction = -1
            Timer.Enabled = True
        End Sub
    
        Private Sub timer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer.Tick
            If Not Timer.Enabled Then
                Return
            End If
            Refresh()
            _currentFrame += _direction
            If _currentFrame = -1 Then
                _currentFrame = 0
                Timer.Enabled = False
                _direction = 0
                Return
            End If
            If _currentFrame = framesCount Then
                _currentFrame = framesCount - 1
                Timer.Enabled = False
                _direction = 0
            End If
        End Sub
    
    #End Region
    
    #Region " Misc "
        Private Shared Function [If](Of T)(ByVal condition As Boolean, ByVal obj1 As T, ByVal obj2 As T) As T
            If condition Then Return obj1
            Return obj2
        End Function
    #End Region
    
    End Class
    Automation Programmer
    Microsoft MVP [2012 - 2018]

  3. #3
    jcgriff2's Avatar
    Join Date
    Feb 2012
    Location
    New Jersey Shore
    Posts
    16,312
    • specs System Specs
      • Manufacturer:
        HP
      • Model Number:
        HP ENVY TouchSmart 17-j130us Notebook - E8A04UA
      • Motherboard:
        HP Insyde 720265-501 6050A2549501-MB-A02
      • CPU:
        Intel Core i7-4700MQ Processor with Turbo Boost up to 3.4GHz.
      • Memory:
        12GB DDR3L SDRAM (2 DIMM)
      • Graphics:
        Intel HD graphics 4600 with up to 1792MB total graphics memory
      • Sound Card:
        Beats Audio quad speakers and two subwoofers
      • Hard Drives:
        1TB 5400RPM hard drive with HP ProtectSmart Hard Drive Protection
      • Disk Drives:
        Hitachi 500 GB SSD; 7 TB USB External
      • Power Supply:
        90w
      • Case:
        Laptop
      • Display:
        17.3-inch diagonal HD+ BrightView LED-backlit touchscreen display (1600 x 900)
      • Operating System:
        Windows 8.1

    Re: [C#/VB.NET] AeroButton Source

    Very nice!!

    BSOD Posting Instructions - Windows 10, 8.1, 8, 7 & Vista ` ` `Carrona Driver Reference Table (DRT)
    https://www.sysnative.com/
    Sysnative Hex-Decimal-UNIX Date Conversion

    Has Sysnative Forums helped you?
    Please consider donating to help support the forum.
    Thank You!

    Microsoft MVP 2009-2015
    Windows Insider MVP 2018 - Present

  4. #4

    Join Date
    Apr 2012
    Location
    United States, TX.
    Age
    25
    Posts
    25

    Re: [C#/VB.NET] AeroButton Source

    A creative approach to a problem with language changes. Very nice.

    By the way, how do you create those animated images? I've seen you post quite a few of them, but can never figure out how you do it .

  5. #5
    jcgriff2's Avatar
    Join Date
    Feb 2012
    Location
    New Jersey Shore
    Posts
    16,312
    • specs System Specs
      • Manufacturer:
        HP
      • Model Number:
        HP ENVY TouchSmart 17-j130us Notebook - E8A04UA
      • Motherboard:
        HP Insyde 720265-501 6050A2549501-MB-A02
      • CPU:
        Intel Core i7-4700MQ Processor with Turbo Boost up to 3.4GHz.
      • Memory:
        12GB DDR3L SDRAM (2 DIMM)
      • Graphics:
        Intel HD graphics 4600 with up to 1792MB total graphics memory
      • Sound Card:
        Beats Audio quad speakers and two subwoofers
      • Hard Drives:
        1TB 5400RPM hard drive with HP ProtectSmart Hard Drive Protection
      • Disk Drives:
        Hitachi 500 GB SSD; 7 TB USB External
      • Power Supply:
        90w
      • Case:
        Laptop
      • Display:
        17.3-inch diagonal HD+ BrightView LED-backlit touchscreen display (1600 x 900)
      • Operating System:
        Windows 8.1

    Re: [C#/VB.NET] AeroButton Source

    Camtasia maybe...?

    BSOD Posting Instructions - Windows 10, 8.1, 8, 7 & Vista ` ` `Carrona Driver Reference Table (DRT)
    https://www.sysnative.com/
    Sysnative Hex-Decimal-UNIX Date Conversion

    Has Sysnative Forums helped you?
    Please consider donating to help support the forum.
    Thank You!

    Microsoft MVP 2009-2015
    Windows Insider MVP 2018 - Present

  6. #6
    AceInfinity's Avatar
    Join Date
    Feb 2012
    Location
    Canada
    Posts
    1,725

    Re: [C#/VB.NET] AeroButton Source

    jcgriff is right I used Camtasia and did an export with the GIF format selected :) However, the quality since it was recording aero, isn't quite perfect, the buttons look even better when you actually see them.
    Automation Programmer
    Microsoft MVP [2012 - 2018]

  7. #7
    jcgriff2's Avatar
    Join Date
    Feb 2012
    Location
    New Jersey Shore
    Posts
    16,312
    • specs System Specs
      • Manufacturer:
        HP
      • Model Number:
        HP ENVY TouchSmart 17-j130us Notebook - E8A04UA
      • Motherboard:
        HP Insyde 720265-501 6050A2549501-MB-A02
      • CPU:
        Intel Core i7-4700MQ Processor with Turbo Boost up to 3.4GHz.
      • Memory:
        12GB DDR3L SDRAM (2 DIMM)
      • Graphics:
        Intel HD graphics 4600 with up to 1792MB total graphics memory
      • Sound Card:
        Beats Audio quad speakers and two subwoofers
      • Hard Drives:
        1TB 5400RPM hard drive with HP ProtectSmart Hard Drive Protection
      • Disk Drives:
        Hitachi 500 GB SSD; 7 TB USB External
      • Power Supply:
        90w
      • Case:
        Laptop
      • Display:
        17.3-inch diagonal HD+ BrightView LED-backlit touchscreen display (1600 x 900)
      • Operating System:
        Windows 8.1

    Re: [C#/VB.NET] AeroButton Source

    Yeah, Camtasia, SnagIt, etc... awesome suite of apps by Tech Smith.

    http://www.techsmith.com/camtasia2-1...FUOo4AodTFSEWw

    BSOD Posting Instructions - Windows 10, 8.1, 8, 7 & Vista ` ` `Carrona Driver Reference Table (DRT)
    https://www.sysnative.com/
    Sysnative Hex-Decimal-UNIX Date Conversion

    Has Sysnative Forums helped you?
    Please consider donating to help support the forum.
    Thank You!

    Microsoft MVP 2009-2015
    Windows Insider MVP 2018 - Present

Similar Threads

  1. .NET Framework
    By Basil in forum General Help & Information
    Replies: 6
    Last Post: 01-10-2013, 01:40 PM
  2. [VB.NET] Form Switcher Fade Module
    By AceInfinity in forum Programming
    Replies: 2
    Last Post: 10-01-2012, 10:11 PM
  3. .NET Could Be Key for Windows on ARM
    By JMH in forum Microsoft News
    Replies: 0
    Last Post: 06-17-2012, 02:59 AM

Log in

Log in