天天看点

在文本框中不能使用粘贴

分享一下实用代码,希望能给大家带来帮助。

设置剪贴板的字符无法向TextBox粘贴的方法。

设置「Ctrl + V」和文本菜单无效的方法

[VB.NET]

''' <summary>

''' 使鼠标和键盘的粘贴无效的TextBox

''' </summary>

Public Class MyTextBox

    Inherits TextBox

    Private pasteKeys As Keys = Keys.V Or Keys.Control

    Public Sub New()

         '设置文本菜单不表示

        Me.ContextMenu = New ContextMenu

     End Sub

    Protected Overrides Function ProcessCmdKey( _

        ByRef msg As Message, ByVal keyData As Keys) As Boolean

        '设置Ctrl+V无效

        If (keyData Or pasteKeys) = pasteKeys Then

             Return True

        Else

            Return MyBase.ProcessCmdKey(msg, keyData)

        End If

    End Function

End Class

[C#]
 
 //using System.Windows.Forms;
 //上面一行写在代码的最上面

 /// <summary>
 ///使鼠标和键盘的粘贴无效的TextBox
 /// </summary>
 public class MyTextBox : TextBox
 {
     const Keys pasteKeys = Keys.V | Keys.Control;

     public MyTextBox() : base()
     {
         //设置文本菜单不表示
         this.ContextMenu = new ContextMenu();
     }

     protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
     {
         //设置Ctrl+V无效
         if ((keyData | pasteKeys) == pasteKeys)
             return true;
         else
             return base.ProcessCmdKey(ref msg, keyData);
     }
 }
      

无视WM_PASTE消息的方法

另外,下面介绍的代码就是设置WM_PASTE消息无视的方法。

[VB.NET]
 
 ''' <summary>
 '''使鼠标和键盘的粘贴无效的TextBox
 ''' </summary>
 Public Class MyTextBox
     Inherits TextBox
     Private WM_PASTE As Integer = &H302

     Protected Overrides Sub WndProc(ByRef m As Message)
         If m.Msg = WM_PASTE Then
             Return
         End If
         MyBase.WndProc(m)
     End Sub
 End Class
      
[C#]
 
 //using System.Windows.Forms;
 //上面一行写在代码的最上面

 /// <summary>
 ///使鼠标和键盘的粘贴无效的TextBox
 /// </summary>
 public class MyTextBox : TextBox
 {
     const int WM_PASTE = 0x302;

     protected override void WndProc(ref Message m)
     {
         if (m.Msg == WM_PASTE)
             return;

         base.WndProc(ref m);
     }
 }
      

.NET Framework 2.0以后版本,使用ShortcutsEnabled属性的方法

从.NET Framework 2.0版本开始,TextBox的类里追回了ShortcutsEnabled属性。当属性设置为false时,在TextBox中使用的快捷键都无法使用。而且,文本菜单也无法表示。所以,字符串粘贴也无法使用。

但是,所有的快捷方式也都无效,复制等操作也无法使用。

继续阅读