【问题标题】:Validating textbox when enter button is pushed按下输入按钮时验证文本框
【发布时间】:2016-08-29 12:38:11
【问题描述】:

我正在为 Autodesk Inventor(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

【问题讨论】:

    标签: vb.net textbox keypress validating


    【解决方案1】:

    我认为你的方法是正确的。为每个 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
    

    【讨论】:

    • 这会不会导致每次击键时,即使它不在text-boxes 我要监视的事件中,也会触发事件?这不会消耗比所需更多的资源吗?
    • 确实如此,但是您可以轻松地在 KeyDown 事件中添加一个测试,以便仅当当前焦点控件是文本框时才将焦点赋予表单
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多