按下输入按钮时验证文本框

时间:2016-08-29 12:38:12

标签: vb.net textbox keypress validating

我正在为Autodesk Inventor创建一个AddIn(3D绘图软件),目前我正在玩位置限制。

我创建了一个自定义用户菜单,用于快速编辑某些值,在本例中为高程和方向值。

首先,我使用textbox.textchanged事件来更改约束值。但这不是100%的工作。按高程1000的示例将改变高程4次(按每个数字)。

现在我开始使用validated event了。这样做效果更好,但我希望在按下Enter按钮时让文本框启动验证。为此,我掀起了这个,但这不正确,我很确定。我该怎么写这个呢?

下面的代码有效,但我希望有一个正确的方法来实现结果。

Private Sub tbElevationValue_TextChanged(sender As Object, e As EventArgs) _
    Handles tbElevation.Validated

    ' If the elevation parameter and textbox value are the same
    ' The sub must be aborted
    If CDbl(tbElevation.Text) = oElevationParameter.Value * 10 Then Exit Sub

    ' Check the entered value
    Dim oValue As Double
    If tbElevation.Text = "" Then
        oValue = 0
        tbElevation.Text = 0
    Else
        oValue = tbElevation.Text
    End If

    ' Set the parameter value
    oElevationParameter.Value = oValue / 10

    ' Update the document
    EM_AddIn.StandardAddInServer.m_inventorApplication.ActiveDocument.Update()

End Sub

Private Sub tbOrientation_TextChanged(sender As Object, e As EventArgs) _
    Handles tbOrientation.Validated

    ' If the orientation parameter and textbox value are the same
    ' The sub must be aborted
    If CDbl(tbOrientation.Text) = cRandiansToDegrees(oOrientationParameter.Value) Then Exit Sub

    ' Check the entered value
    Dim oValue As Double
    If tbOrientation.Text = "" Then
        oValue = 0
        tbOrientation.Text = 0
    Else
        oValue = tbOrientation.Text
    End If

    ' Set the parameter value
    oOrientationParameter.Value = cDegreesToRandians(oValue)

    ' Update the document
    EM_AddIn.StandardAddInServer.m_inventorApplication.ActiveDocument.Update()

End Sub

Private Sub OrientationElevationEnterKey_Pressed(sender As Object, e As Windows.Forms.KeyEventArgs) Handles tbElevation.KeyUp, tbOrientation.KeyUp

    If e.KeyCode = Windows.Forms.Keys.Enter Then

        CType(sender, Windows.Forms.TextBox).Parent.Focus()
        CType(sender, Windows.Forms.TextBox).Focus()

    End If


End Sub

1 个答案:

答案 0 :(得分:0)

我认为你的方式正确。为每个TextBox对象注册key_down事件可能会很痛苦,但你的想法很好。

您可以将key_down事件侦听器设置为您的表单。

尝试这样的事情:

Private Sub Main_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
    If e.KeyCode = Keys.KeyCode.Enter Then

        MyBase.Focus() ' this will cause the currently focused control to validate

    End If     
End Sub