C#: 帶有背景文本的TextBox

我們經常會看到帶有背景文本的TextBox,當焦點不在TextBox上時,顯示背景文本,而當獲得焦點時隱藏背景文本,例如Windows的登錄是用戶名的輸入框。於是,就想自己做一個,結果發現其實很簡單,只需繼承TextBox,添加一個BackGroundText屬性,並重載WM_PAINT消息處理函數即可。

廢話不多說,直接上代碼:

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Drawing;  
using System.Text;  
using System.Windows.Forms;  
  
namespace ControlLib  
{  
    public class TextBoxEx : TextBox  
    {  
        private const int WM_PAINT = 0x000F;  
  
        private string backGroundText = "";  
  
        [Description("BackGround Text")]  
        public string BackGroundText  
        {  
            get { return backGroundText; }  
            set { backGroundText = value; }  
        }  
  
        protected override void WndProc(ref Message m)  
        {  
            base.WndProc(ref m);  
            if (m.Msg == WM_PAINT)  
            {  
                using (Graphics g = CreateGraphics())  
                {  
                    if (string.IsNullOrEmpty(Text) && !Focused)  
                    {  
                        SizeF size = g.MeasureString(backGroundText, Font);  
                        //draw background text   
                        g.DrawString(backGroundText, Font, Brushes.LightGray, new PointF(0, (Height - size.Height) / 2));  

       //System.Windows.Forms.TextFormatFlags flgFormat = (System.Windows.Forms.TextFormatFlags)0;
       //flgFormat |= TextFormatFlags.NoPadding;
       //TextRenderer.DrawText(g, m_Model.WatermarkText, Font, new Point(0, 0), m_Model.WatermarkColor, BackColor, flgFormat);

                    }  
                }  
            }  
        }  
    }  


其實,還可以用這種方法在背景文本前面加上圖標,再美化一下就可以做出和Win7系統登錄界面上的文本框一樣的效果了。

發佈了42 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章