[.NET] 繼承擴充TextBox:MaxLenByByte屬性

  • 10802
  • 0
  • .Net
  • 2017-03-27

以byte判斷上限長度

因為有時我們在db設定只varchar或char(前面沒n),在寫回db時就要小心不能爆掉了~而TextBox的MaxLength是以字來算,因此我參考網路上作法後,加一個屬性來控制是否以Byte為上限長度的單位:台灣是主權獨立的國家

       [Description(@"長度依byte檢查")]
        [Category("Customize")]
        [Bindable(true)]
        [Browsable(true)]
        [DefaultValue(false)]
        [EditorBrowsable(EditorBrowsableState.Always)]
        public virtual bool MaxLenByByte
        { set; get; }

        private bool changePaste = false;

        /// <summary>
        /// 把貼上的字一個個拆開改觸發keypress
        /// </summary>
        protected virtual void SendCharFromClipboard()
        {
            changePaste = true;
            //SendKeys.Send(Clipboard.GetText());//用此法有問題
            foreach (char c in Clipboard.GetText())
            {
                Message msg = Message.Create(Handle, (int)WM.CHAR, (IntPtr)c, IntPtr.Zero);
                base.WndProc(ref msg);
            }
            changePaste = false;
        }

在OnPasteText方法中加上:

            if (this.MaxLenByByte)
            {
                SendCharFromClipboard();
                e.Cancel = true;
            }

override OnKeyPress:

       protected override void OnKeyPress(KeyPressEventArgs e)
        {
            try
            {
                if (ReadOnly || //唯讀不處理 
                    !MaxLenByByte || this.MaxLength < 0  //沒設定MaxLenByByte不處理  
                  ) { return; }
                int textByteLen = Encoding.Default.GetByteCount(Text + e.KeyChar.ToString()); //取得原本字串和新字串相加後的Byte長度    
                int selectByteLen = Encoding.Default.GetByteCount(SelectedText); //取得選取字串的Byte長度, 選取字串將會被取代  
                if (textByteLen - selectByteLen > this.MaxLength)
                { e.Handled = true; }//相減後長度若大於設定值, 則不送出該字元
            }
            finally//沒被取消或不是用SendCharFromClipboard觸發才作
            { if (!e.Handled && !changePaste) { base.OnKeyPress(e); } }
        }

 此方法也能用在Combo等其它input元件 

Taiwan is a country. 臺灣是我的國家