代码改变世界

加下划线的TextBox

2010-03-01 13:39  爱研究源码的javaer  阅读(406)  评论(0编辑  收藏  举报

 public partial class UCTextBox : TextBox
    {
        public UCTextBox()
        {
            InitializeComponent();

            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);

            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

            this.BorderStyle = BorderStyle.None;

        }

        public bool DrawLine
        {
            get { return this.m_DrawLine; }

            set { this.m_DrawLine = value; this.Invalidate(); }

        }

        private bool m_DrawLine = false;

        private const int WM_NCPAINT = 0x0085;

        private const int WM_CHAR = 0x0102;

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern IntPtr GetWindowDC(IntPtr hWnd);

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            if (m.Msg == 0xf || m.Msg == 0x133)
            {
                if (this.DrawLine)
                {
                    IntPtr hDC = GetWindowDC(m.HWnd);

                    if (hDC.ToInt32() == 0)
                    {
                        return;
                    }

                    Graphics g = Graphics.FromHdc(hDC);

                    Brush b = Brushes.Black;

                    Pen p = new Pen(b, 1);

                    Point p1 = new Point(0, this.Height - 1);

                    Point p2 = new Point(this.Width, Height - 1);

                    g.DrawLine(p, p1, p2);

                    m.Result = IntPtr.Zero;

                    ReleaseDC(m.HWnd, hDC);
               
                }
            }
        }

        private Color backColor = System.Drawing.SystemColors.Control;

        public override Color BackColor
        {
            get
            {
                return backColor;
            }
            set
            {
                backColor = value;

                Invalidate();
            }
        }
    }