■ はじめに
https://blogs.yahoo.co.jp/dk521123/21165720.htmlでユーザコントロールを作成したが、 今回は既存のコントロールを継承するカスタムコントロールについて調べる
■ 作成および使用方法
【1】 既存のコントロールを継承する
public class CustomTextBox : TextBox // TextBoxを継承する
【2】 自分好みにプログラミングする
* 以下サンプルを参照のこと
【3】 ソリューションのビルドをする
* ツールボックスに歯車型のコンポーネントが追加されるので、 これをフォームにドラッグ&ドロップ!
■ サンプル
* 表示しきれないPathの場合、"..."を表示する
CustomTextBox.cs
public class CustomTextBox : TextBox { public CustomTextBox() { this.TextChanged += new EventHandler(CustomTextBox_TextChanged); this.Leave += new EventHandler(CustomTextBox_Leave); } private void CustomTextBox_TextChanged(object sender, EventArgs e) { this.PathEllipsis(this.Text, this.Font, this.Size); } private void CustomTextBox_Leave(object sender, EventArgs e) { this.Text = this.PathEllipsis(this.Text, this.Font, this.Size); } private string PathEllipsis(string text, Font font, Size size) { TextRenderer.MeasureText( text, font, size, TextFormatFlags.PathEllipsis | TextFormatFlags.ModifyString); return text; } }参考資料
http://www.codeproject.com/KB/vb/NewPathCompactPath.aspx
http://dobon.net/vb/dotnet/graphics/stringtrimming.html
■ プロパティを追加したい場合
[Category("表示")] [DefaultValue(typeof(Color), "DarkGray")] [Description("説明文")] [RefreshProperties(RefreshProperties.Repaint)] public Color CustomBackColor { get { return this.CustomBackColor; } set { this.CustomBackColor = value; } }
■ イベントを修正したい場合
protected override void OnEnter(EventArgs e) { if (string.IsNullOrEmpty(this.Text)) { base.BackColor = this.CustomBackColor; } base.OnEnter(e); }
参考文献
http://kbdpage.blog82.fc2.com/blog-entry-122.htmlhttp://pcnetbeginners.seesaa.net/article/173807800.html
http://youryella.wankuma.com/Library/Extensions/TextBox/SystemWatermark.aspx