1. Add the Watermarktextbox class to the new project:
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Drawing;usingSystem.ComponentModel;namespacetextboxwatermark{[ToolboxBitmap (typeof(TextBox))] Public classWatermarktextbox:textbox {Private string_emptytexttip; PrivateColor _emptytexttipcolor =Color.darkgray; Private Const intWM_PAINT =0xF; PublicWatermarktextbox ():Base() {} [DefaultValue ("")] Public stringEmptytexttip {Get{return_emptytexttip;} Set{_emptytexttip=value; Base. Invalidate (); }} [DefaultValue (typeof(Color),"Darkgray")] PublicColor Emptytexttipcolor {Get{return_emptytexttipcolor;} Set{_emptytexttipcolor=value; Base. Invalidate (); } } protected Override voidWndProc (refMessage m) { Base. WndProc (refm); if(M.msg = =wm_paint) {Wmpaint (refm); } } Private voidWmpaint (refMessage m) { using(Graphics graphics = Graphics.fromhwnd (Base. Handle)) {if(Text.length = =0&&!string. IsNullOrEmpty (_emptytexttip)&&!Focused) {textformatflags format=textformatflags.endellipsis|Textformatflags.verticalcenter; if(RightToLeft = =righttoleft.yes) {format|= Textformatflags.righttoleft |Textformatflags.right; } textrenderer.drawtext (Graphics, _emptytexttip, Font,Base. ClientRectangle, _emptytexttipcolor, format); } } } }}
2. Instantiate the control in the form and add:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;namespacetextboxwatermark{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); Textboxwatermark.watermarktextbox Tbname=NewWatermarktextbox (); Tbname.emptytexttip="Please enter your account number."; Tbname.location=NewSystem.Drawing.Point ( the, the); Tbname.size=NewSystem.Drawing.Size ( Max, +); Tbname.name="Tbname"; Tbname.tabstop=false; //tbname.tabindex = 0; This. Controls.Add (Tbname); Textboxwatermark.watermarktextbox Tbpassword=NewWatermarktextbox (); Tbpassword.emptytexttip="Please enter your password."; Tbpassword.location=NewSystem.Drawing.Point ( the, -); Tbpassword.size=NewSystem.Drawing.Size ( Max, +); Tbpassword.name="Tbpassword"; Tbpassword.tabstop=false; //tbname.tabindex = 0; This. Controls.Add (Tbpassword); } }}
C # WinForm textbox add watermark Effect