In some software, we can see that when an input control (textbox) does not have input and has no focus, it will display some hints, some of which are implemented with composite controls, and it is easy to implement the TextBox control directly.
The following describes how to implement this control.
The first step: we build a class that inherits the TextBox, named Watermaktextbox.
The second step: Add two attributes to this class, one is emptytexttip, that is, when the control has no input and no focus, the hint text is displayed, that is, the watermark, and the other is Emptytexttipcolor, is the color of the hint text.
The third step: the most important step is to rewrite the wndproc function, intercept the WM_PAINT message, when there is no input and input focus, redraw the textbox, see the following code:
protected Override voidWndProcrefmessage m) { Base. WndProc (refm); if(M.msg = =wm_paint) {Wmpaint (refm); }} Private voidWmpaint (refmessage m) {Rectangle Rectangle=NewRectangle0,0, width, height); 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); } }
C # WinForm Control Landscaping Extension series to TextBox plus watermark