99 lines
2.6 KiB
C#
99 lines
2.6 KiB
C#
using System;
|
|||
|
|
using System.Collections.Generic;
|
||
|
|
using System.ComponentModel;
|
||
|
|
using System.Drawing;
|
||
|
|
using System.Linq;
|
||
|
|
using System.Text;
|
||
|
|
using System.Threading.Tasks;
|
||
|
|
using System.Windows.Forms;
|
||
|
|
|
||
|
|
namespace JYControl
|
||
|
|
{
|
||
|
|
/// <summary>
|
||
|
|
/// TextBox添加水印文字
|
||
|
|
/// </summary>
|
||
|
|
[ToolboxBitmap(typeof(TextBox))]
|
||
|
|
|
||
|
|
public class WatermarkTextBox : TextBox
|
||
|
|
{
|
||
|
|
private string _watermark;
|
||
|
|
private Color _watermarkColor = Color.DarkGray;
|
||
|
|
private const int WM_PAINT = 0xF;
|
||
|
|
|
||
|
|
public WatermarkTextBox()
|
||
|
|
: base()
|
||
|
|
{
|
||
|
|
}
|
||
|
|
/// <summary>
|
||
|
|
/// 输入需要显示水印文字
|
||
|
|
/// </summary>
|
||
|
|
///
|
||
|
|
[Category("控件属性")]
|
||
|
|
[Description("输入需要显示水印文字")]
|
||
|
|
[DefaultValue("")]
|
||
|
|
public string Watermark
|
||
|
|
{
|
||
|
|
get { return _watermark; }
|
||
|
|
set
|
||
|
|
{
|
||
|
|
_watermark = value;
|
||
|
|
base.Invalidate();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// 改变水印文字的颜色
|
||
|
|
/// </summary>
|
||
|
|
///
|
||
|
|
[Category("控件属性")]
|
||
|
|
[Description("改变水印文字的颜色")]
|
||
|
|
[DefaultValue(typeof(Color), "DarkGray")]
|
||
|
|
public Color WatermarkColor
|
||
|
|
{
|
||
|
|
get { return _watermarkColor; }
|
||
|
|
set
|
||
|
|
{
|
||
|
|
_watermarkColor = value;
|
||
|
|
base.Invalidate();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
protected override void WndProc(ref Message m)
|
||
|
|
{
|
||
|
|
base.WndProc(ref m);
|
||
|
|
if (m.Msg == WM_PAINT)
|
||
|
|
{
|
||
|
|
WmPaint(ref m);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private void WmPaint(ref Message m)
|
||
|
|
{
|
||
|
|
using (Graphics graphics = Graphics.FromHwnd(base.Handle))
|
||
|
|
{
|
||
|
|
if (Text.Length == 0
|
||
|
|
&& !string.IsNullOrEmpty(_watermark)
|
||
|
|
&& !Focused)
|
||
|
|
{
|
||
|
|
TextFormatFlags format =
|
||
|
|
TextFormatFlags.EndEllipsis |
|
||
|
|
TextFormatFlags.VerticalCenter;
|
||
|
|
|
||
|
|
if (RightToLeft == RightToLeft.Yes)
|
||
|
|
{
|
||
|
|
format |= TextFormatFlags.RightToLeft | TextFormatFlags.Right;
|
||
|
|
}
|
||
|
|
|
||
|
|
TextRenderer.DrawText(
|
||
|
|
graphics,
|
||
|
|
_watermark,
|
||
|
|
Font,
|
||
|
|
base.ClientRectangle,
|
||
|
|
_watermarkColor,
|
||
|
|
format);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|