在.net C# 裡怎麼重寫一個TextBox控制項

來源:互聯網
上載者:User
using     System;      
using     System.Drawing;      
using     System.Windows.Forms;      
   
namespace     ManuApp      
{      
  ///     <summary>      
  ///     TextBoxNoManu     的摘要說明。      
  ///     </summary>      
  public     class     TextBoxNoManu:System.Windows.Forms.TextBox      
  {      
    public     TextBoxNoManu()      
    {      
        //      
        //     TODO:     在此處添加建構函式邏輯      
        //      
    }      
    protected     override     void     WndProc(ref     Message     m)      
    {      
        if(m.Msg     !=     0x007B)      
        {      
            base.WndProc     (ref     m);      
        }      
    }      

  }      
}  

自訂TextBox控制項的外觀(需要重寫訊息迴圈)

using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace windowsTest
{

    [ToolboxItem(true)]
    public class WTextBox : System.Windows.Forms.TextBox
    {        
        [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);
       
        private Color _BorderColor = Color.FromArgb(0xA7, 0xA6, 0xAA);
        private Color _HotColor = Color.Green;       
       
        private new BorderStyle BorderStyle
        {
            get { return BorderStyle.FixedSingle; }
        }

        #region       

        [Category("Appearance"),
       Description("Border color, Only for BorderStyle equal FixedSingle"),
      DefaultValue(typeof(Color), "#A7A6AA")]
        public Color BorderColor
        {
            get
            {
                return this._BorderColor;
            }
            set
            {
                this._BorderColor = value;
                this.Invalidate();
            }
        }
       
        [Category("Appearance"),
       Description("Hot color, Only for BorderStyle equal FixedSingle"),
    DefaultValue(typeof(Color), "#996699")]
        public Color HotColor
        {
            get
            {
                return this._HotColor;
            }
            set
            {
                this._HotColor = value;
                this.Invalidate();
            }
        }
        #endregion

       
        public WTextBox()
            : base()
        {
        }

        protected override void OnMouseHover(EventArgs e)
        {
            base.OnMouseHover(e);

            if (string.IsNullOrEmpty(this.SelectedText))
                this.Cursor = Cursors.SizeAll;
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);

            int _HotBlur = this.Height /4;

            if (e.X < this.Width + _HotBlur && e.X > this.Width - _HotBlur)
                this.Cursor = Cursors.SizeWE;
            else
            {
                if ((e.X > _HotBlur && e.X < this.Width - _HotBlur) || (e.Y > _HotBlur && e.Y < this.Height - _HotBlur))
                    this.Cursor = Cursors.IBeam;
                else
                    this.Cursor = Cursors.SizeAll;
            }
        }
      
        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);           
            this.Cursor = Cursors.IBeam;
        }

        protected override void WndProc(ref Message m)
        {

            base.WndProc(ref m);

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

                if (this.BorderStyle == BorderStyle.FixedSingle)
                {                       
                    System.Drawing.Graphics g = Graphics.FromHdc(hDC);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                   
                    g.DrawRectangle(new Pen(this._BorderColor, 1), 0, 0, this.Width - 1, this.Height - 1);

                    g.DrawLine(new Pen(this._HotColor , 2), new Point(this.Width - 1, this.Height / 4), new Point(this.Width - 1, this.Height / 4 * 3));                   
                   
                }

                m.Result = IntPtr.Zero;

                ReleaseDC(m.HWnd, hDC);
            }
        }

    }
}

一個只能接收某些字元的textbox

經常某些輸入的文本要求只能是數字等,比如qq登陸框上的qq帳號,如果按鍵不是數字,則沒有反應。原理當然是很簡單的,只需要在相應訊息到來時阻止控制項去處理訊息即可。

這種例子很多,當然可以override keypress事件。也可以從textbox繼承一個類,然後重寫wndpro,從而無視某些訊息。
最重要的訊息是WM_CHAR。此外,還有幾個特殊按鍵是永遠不能屏蔽的,分別是backspace, delete,此外還有快速鍵,ctrl-a,
ctrl-c,ctrl-x,ctrl-v.再此外,我們還要在執行粘貼時對文本做一次判斷,不合法文本則被忽略。

可以用一個FilterString的string來記錄合法字元,不在此字串中認為是不接受的字元,

       /// <summary>
        /// 覆蓋視窗過程!處理WM_CHAR訊息!
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            int charcode = (int)m.WParam;
            switch (m.Msg)
            {
                case WM_CHAR:
                    // 遇到非法字元,直接return即可過濾非法字元!break表示處理該字元
                    //屏蔽小數點
                    if (charcode == (int)Keys.Decimal)
                        return;

                    // 注意delete,backspace字元不能過濾!!!
                    // ctrl-a,ctrl-c,ctrl-v快速鍵操作不能屏蔽!
                    if (charcode == (int)Keys.Back || charcode == (int)Keys.Delete)
                        break;

                    //如果按下了CTRL鍵
                    if (charcode == 1     //ctrl a
                        || charcode == 3   //ctrl c
                        || charcode == 22  //ctrl v
                        || charcode == 24    //ctrl x
                        )
                        break;

                    if (this.m_FilterStr.IndexOf((char)charcode) < 0)
                        return;
                    break;

                case WM_KEYDOWN:
                    //ctrl-A 全選
                    if (Control.ModifierKeys == Keys.Control)
                    {
                        if(charcode==(int)Keys.A)
                            this.SelectAll();
                    }
                    break;

                case WM_PASTE:
                    //粘貼訊息
                    IDataObject obj = Clipboard.GetDataObject();
                    if (obj == null)
                        return;
                    if (obj.GetDataPresent(DataFormats.Text))
                    {
                        string text = obj.GetData(DataFormats.Text) as string;
                        if (text == null)
                            return;
                        foreach (char c in text)
                        {
                            //查看是否含有過濾字元以外的字元!
                            if (this.m_FilterStr.IndexOf(c) < 0)
                                return;
                        }
                    }
                    break;
            }            
            //處理訊息
            base.WndProc(ref m);
        }

                          【reprinted from http://lenny119.blog.sohu.com】

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.