public partial class MyTextBox : System.Windows.Forms.TextBox, ISupportInitialize
{
public MyTextBox() : base()
{
}
private Color _disableBackColor = System.Drawing.SystemColors.Window;
[Category("表示"), Description("コンポーネントの使用不可時の背景色です。")]
public Color DisableBackColor
{
get { return _disableBackColor; }
set { _disableBackColor = value; }
}
private Color _disableForeColor = System.Drawing.SystemColors.WindowText;
[Category("表示"), Description("テキストを表示するのに使用される、このコンポーネントの使用不可時の前景色です。")]
public Color DisableForeColor
{
get { return _disableForeColor; }
set { _disableForeColor = value; }
}
private bool initialLayout = false;
protected override void OnEnabledChanged(EventArgs e)
{
base.OnEnabledChanged(e);
if (initialLayout)
{
if (this.Enabled)
{
this.BackColor = this.BackColor;
this.SetStyle(ControlStyles.UserPaint, false);
base.RecreateHandle();
}
else
{
this.BackColor = this.DisableBackColor;
this.SetStyle(ControlStyles.UserPaint, true);
base.RecreateHandle();
}
}
else
{
this.SetStyle(ControlStyles.UserPaint, true);
}
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
base.OnPaintBackground(pevent);
using (Brush backBrush = new SolidBrush(this.DisableBackColor))
pevent.Graphics.FillRectangle(backBrush , 0, 0, this.Width - 1, this.Height - 1);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
TextFormatFlags tff = TextFormatFlags.VerticalCenter;
switch (this.TextAlign)
{
case HorizontalAlignment.Center:
tff |= TextFormatFlags.HorizontalCenter;
break;
case HorizontalAlignment.Left:
tff |= TextFormatFlags.Left;
break;
case HorizontalAlignment.Right:
tff |= TextFormatFlags.Right;
break;
}
if (this.Multiline)
{
tff |= TextFormatFlags.WordBreak;
}
using (Graphics g = CreateGraphics())
using (Brush backBrush = new SolidBrush(this.BackColor))
{
DateTime dtVal;
decimal dcVal;
if (DateTime.TryParse(this.Text, out dtVal))
{
TextRenderer.DrawText(g, dtVal.ToString("yyyy/MM/dd"),
this.Font, this.ClientRectangle, this.DisableForeColor, tff);
}
else if (decimal.TryParse(this.Text, out dcVal))
{
TextRenderer.DrawText(g, dcVal.ToString("#,##0"),
this.Font, this.ClientRectangle, this.DisableForeColor, tff);
}
else
{
TextRenderer.DrawText(g, this.Text,
this.Font, this.ClientRectangle, this.DisableForeColor, tff);
}
}
}
#region ISupportInitialize メンバ
public void BeginInit()
{
initialLayout = false;
}
public void EndInit()
{
if (!initialLayout)
{
initialLayout = true;
if (this.Enabled)
{
this.BackColor = this.BackColor;
this.SetStyle(ControlStyles.UserPaint, false);
base.RecreateHandle();
}
else
{
this.BackColor = this.DisableBackColor;
this.SetStyle(ControlStyles.UserPaint, true);
base.RecreateHandle();
}
}
}
#endregion
}