我在Windows窗体中有一个设置为多行的文本框。我有一个KeyDown
事件处理程序,它可以识别Enter文本框中的键并执行某些操作,然后从文本框中清除文本。如何以编程方式将插入符号移动到文本框的开头?当我在文本框中按Ctrl + Home时,可以看到它。我尝试使用SelectionStart
属性下面的内容,但它将光标留在第二行的开头。
Private Sub txtComments_KeyDown(sender As Object, e As KeyEventArgs) Handles txtComments.KeyDown
If e.KeyCode = Keys.Enter Then
If txtComments.TextLength > 0 Then
AddSelection(txtComments.Text)
txtComments.Clear()
End If
If txtComments.TextLength = 0 Then
txtComments.Focus()
txtComments.SelectionStart = 0
End If
End If
End Sub
问题是因为您要在基础控件处理实际事件之前清除控件并在控件的开始处集中精力KeyPress
,所以在所有代码运行后按Enter仍会向控件添加新行,这就是为什么结束于第二行。
您可以通过使用防止这种行为SuppressKeyPress
性质的KeyEventArgs
到您的事件处理程序通过:
Private Sub txtComments_KeyDown(sender As Object, e As KeyEventArgs) Handles txtComments.KeyDown
If e.KeyCode = Keys.Enter Then
If txtComments.TextLength > 0 Then
AddSelection(txtComments.Text)
txtComments.Clear()
e.SuppressKeyPress = True
End If
End If
End Sub
该属性的文档说:
获取或设置一个值,该值指示是否应将键事件传递给基础控件。
和:
您可以在事件处理程序(例如KeyDown)中将true分配给此属性,以防止用户输入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句