Watermark effect of the Winform Control
In our project, it is very common to plot the watermark effect for the control. Next I will discuss how to create the watermark effect. In fact, in most cases, only the drop-down box and input box use watermarks. For example, we can see Sina mail, as shown in Figure 1 ).
The following code implements the watermark effect in the input box:
Using System. Drawing;
Using System. Windows. Forms;
Namespace TextBoxWithWaterkmarkExample
{
/// <Summary>
/// TextBox with watermark Effect
/// </Summary>
Public class TextBoxWithWaterkmark: TextBox
{
/// <Summary>
/// The internal object of the watermark, including the text color.
/// </Summary>
Private Brush WatermarkBrush {get {return new SolidBrush (Color. Gray );}}
/// <Summary>
/// Watermark text format.
/// </Summary>
Public Font WatermarkFont {get; set ;}
/// <Summary>
/// Watermark content.
/// </Summary>
Public string WatermarkContext {get; set ;}
Protected override void WndProc (ref Message m)
{
Base. WndProc (ref m );
If (this. WatermarkBrush = null | this. WatermarkFont = null | this. WatermarkContext = null)
{Return ;}
// Obtain the length of the text related to a window does not contain null characters)
Int WM_PAINT = 0xF;
// Lose focus
Int WM_KILLFOCUS = 0x8;
If (m. Msg = WM_KILLFOCUS & string. IsNullOrEmpty (base. Text ))
| (M. Msg = WM_PAINT & string. IsNullOrEmpty (base. Text )&&! Base. Focused ))
{
Rectangle rect = base. ClientRectangle;
Using (Graphics g = base. CreateGraphics ())
{
G. DrawString (
This. WatermarkContent,
This. WatermarkFont,
This. WatermarkBrush,
Rect );
}
}
}
}
}
We can see that, by rewriting the WndProc function, m. Msg is judged. when the focus is lost and the text in the input box is empty, the text is drawn through GDI +. Or you can draw a text when the text is not empty.
This article is from the "Zhang Xiaoyong" blog and will not be reproduced!