Public Class uTextBox
Inherits System.Windows.Forms.TextBox
Public Property MaxByteLength As UInteger
Private Const WM_PASTEDATA As Integer = &H302 ' //貼上資料的訊息
Private Const WM_CHAR As Integer = &H102
Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
MyBase.OnKeyPress(e)
If Me.ReadOnly Then Return '//唯讀不處理
If (_MaxByteLength = 0) Then Return '//沒設定MaxByteLength不處理
If (Char.IsControl(e.KeyChar)) Then Return ' //Backspace, Enter...等控制鍵不處理
Dim textByteLength As Integer = System.Text.Encoding.GetEncoding(950).GetByteCount(Text + e.KeyChar.ToString()) '//取得原本字串和新字串相加後的Byte長度
Dim selectTextByteLength As Integer = System.Text.Encoding.GetEncoding(950).GetByteCount(SelectedText) '//取得選取字串的Byte長度, 選取字串將會被取代
If (textByteLength - selectTextByteLength > _MaxByteLength) Then e.Handled = True ' //相減後長度若大於設定值, 則不送出該字元
End Sub
Protected Overrides Sub WndProc(ByRef m As Message)
If m.Msg = WM_PASTEDATA Then '//如果收到貼上資料的訊息, 包括Ctrl+V, Shift+Ins和滑鼠右鍵選單中的貼上
Me.SendCharFromClipboard() '//就把剪貼簿中的字串一個字元一個字元的拆開, 再傳給自己 SendCharFromClipboard()
Else
MyBase.WndProc(m)
End If
End Sub
Private Sub SendCharFromClipboard()
For Each c As Char In Clipboard.GetText()
Dim msg As Message = New Message()
msg.HWnd = Handle
msg.Msg = WM_CHAR
msg.WParam = CType(Asc(c), IntPtr)
msg.LParam = IntPtr.Zero
MyBase.WndProc(msg)
Next
End Sub
Public Class uTextBox
Inherits System.Windows.Forms.TextBox
Public Property MaxByteLength As UInteger
Private Const WM_PASTEDATA As Integer = &H302 ' //貼上資料的訊息
Private Const WM_CHAR As Integer = &H102
Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
MyBase.OnKeyPress(e)
If Me.ReadOnly Then Return '//唯讀不處理
If (_MaxByteLength = 0) Then Return '//沒設定MaxByteLength不處理
If (Char.IsControl(e.KeyChar)) Then Return ' //Backspace, Enter...等控制鍵不處理
Dim textByteLength As Integer = System.Text.Encoding.GetEncoding(950).GetByteCount(Text + e.KeyChar.ToString()) '//取得原本字串和新字串相加後的Byte長度
Dim selectTextByteLength As Integer = System.Text.Encoding.GetEncoding(950).GetByteCount(SelectedText) '//取得選取字串的Byte長度, 選取字串將會被取代
If (textByteLength - selectTextByteLength > _MaxByteLength) Then e.Handled = True ' //相減後長度若大於設定值, 則不送出該字元
End Sub
Protected Overrides Sub WndProc(ByRef m As Message)
If m.Msg = WM_PASTEDATA Then '//如果收到貼上資料的訊息, 包括Ctrl+V, Shift+Ins和滑鼠右鍵選單中的貼上
Me.SendCharFromClipboard() '//就把剪貼簿中的字串一個字元一個字元的拆開, 再傳給自己 SendCharFromClipboard()
Else
MyBase.WndProc(m)
End If
End Sub
Private Sub SendCharFromClipboard()
For Each c As Char In Clipboard.GetText()
Dim msg As Message = New Message()
msg.HWnd = Handle
msg.Msg = WM_CHAR
msg.WParam = CType(Asc(c), IntPtr)
msg.LParam = IntPtr.Zero
MyBase.WndProc(msg)
Next
End Sub