我正在尝试创建TextBox,以便用户无法键入任何内容,但他们应该能够使用剪贴板文本粘贴信息。
答案 0 :(得分:2)
您可以订阅TextBox' KeyPress
event,其中始终将e.Handled
属性设置为True,除非您按剪贴板组合(CTRL + C,V)。< / p>
要识别剪贴板组合,您还必须订阅KeyDown
event,您可以在其中识别按下了哪个键或组合键,然后通过Boolean
变量(您从KeyPress
事件中读取,您可以指示是否允许组合。
执行我刚才描述的操作会导致任何键盘输入(即不是CTRL + C或CTRL + V)到而不是由TextBox处理,因此它不会添加任何字符除非你粘贴。
Dim InputIsCommand As Boolean = False
Private Sub TextBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
InputIsCommand = e.Control = True AndAlso (e.KeyCode = Keys.V OrElse e.KeyCode = Keys.C)
End Sub
Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = Not InputIsCommand
End Sub
C#版本:
public Form1() //Form constructor.
{
InitializeComponent();
textBox1.KeyPress += textBox1_KeyPress;
textBox1.KeyDown += textBox1_KeyDown;
}
bool InputIsCommand = false;
private void textBox1_KeyDown(Object sender, System.Windows.Forms.KeyEventArgs e)
{
InputIsCommand = e.Control == true && (e.KeyCode == Keys.V || e.KeyCode == Keys.C);
}
private void textBox1_KeyPress(Object sender, System.Windows.Forms.KeyPressEventArgs e)
{
e.Handled = !InputIsCommand;
}