【问题标题】:How to move the caret to the beginning of a multiline textbox?如何将插入符号移动到多行文本框的开头?
【发布时间】:2015-12-30 17:06:10
【问题描述】:

我在 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

【问题讨论】:

    标签: .net vb.net winforms


    【解决方案1】:

    问题是因为您正在清除控件并将焦点放在控件的开头之前实际的KeyPress 事件由底层控件处理,因此按 Enter kbd> 仍然会在所有代码运行后 向控件添加新行,这就是您最终出现在第二行的原因。

    您可以使用传入事件处理程序的KeyEventArgsSuppressKeyPress property 来防止这种行为:

    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 分配给此属性,以防止用户输入。

    【讨论】:

    • @Jyina 没问题。我刚刚编辑了答案 - 事件处理程序中的代码可以短得多 - 无需检查长度 = 0 或重新聚焦在控件中。
    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多