Watermark effect of the Winform Control

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.