Sourcecode - AutoSizedButton
Download AutoSizedButton.cs
// Copyright (C) 2004 Daniel Grunwald
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// For more information read the file "LICENSE.txt".
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Grunwald.Gui.Controls
{
/// <summary>
/// A button that automatically resizes to fit its text.
/// </summary>
public class AutoSizedButton : Button
{
int defaultWidth;
/// <summary>
/// Creates a new AutoSizedButton.
/// </summary>
public AutoSizedButton()
{
this.FlatStyle = FlatStyle.System;
defaultWidth = this.Width;
}
/// <summary>
/// Creates a new AutoSizedButton with the specified text.
/// </summary>
public AutoSizedButton(string text) : this()
{
this.Text = text;
}
/// <summary>
/// Raises the <see cref="Control.TextChanged"/> event.
/// </summary>
protected override void OnTextChanged(System.EventArgs e)
{
base.OnTextChanged(e);
using (Graphics g = CreateGraphics()) {
SizeF size = g.MeasureString(this.Text, this.Font);
int w = ((int)Math.Ceiling(size.Width / 8.0) + 1) * 8;
if (this.Text != "...") {
if (w < defaultWidth) w = defaultWidth;
}
if (w != this.Width)
this.Width = w;
}
}
}
}