文本框vb.net的两种事件处理输入和离开

时间:2018-09-24 23:38:09

标签: vb.net if-statement events handler enter

我正在与Enter一起在一个函数中使用两种类型的事件处理LeaveIf-Statement

任何人,请更正我的脚本。

Private Sub MaskedTextBox_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OrgNameTextBox.Enter, OrgNameTextBox.Leave        
    If Event = Enter Then
        CType(sender, Control).BackColor = Color.Yellow
        CType(sender, Control).ForeColor = Color.Black

    ElseIf  Event = Leave Then
        CType(sender, Control).BackColor = Color.Black
        CType(sender, Control).ForeColor = Color.White

    End If
End Sub

1 个答案:

答案 0 :(得分:0)

理想情况下,您应该为两个单独的事件使用两个单独的处理程序,因为您在不同的事件上执行不同的操作。但是,如果您必须只有一个处理程序,则可以尝试类似的操作,而且我很确定这是一个HACK:

Private Sub MaskedTextBox_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OrgNameTextBox.Enter, OrgNameTextBox.Leave
 Dim stackTrace As New StackTrace(True)
 Dim frame As StackFrame = stackTrace.GetFrames[0]
 If(frame.GetMethod.Name = 'OnEntered') <CHECK THE EVENT NAME, THIS IS JUST AN EXAMPLE>
            CType(sender, Control).BackColor = Color.Yellow
            CType(sender, Control).ForeColor = Color.Black
 End If
 If(frame.GetMethod.Name = 'OnLeave')        
            CType(sender, Control).BackColor = Color.Black
            CType(sender, Control).ForeColor = Color.White
 End If
End Sub

我已经看到了仅在StackOverflow中获取事件名称的方法,一旦找到正确的名称就会更新答案:)

编辑后的答案

Private Sub MaskedTextBox_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OrgNameTextBox.Enter, OrgNameTextBox.Leave
     Dim stackTrace As New StackTrace(True)
     For Each frame As StackFrame In s.GetFrames
      IF(frame.GetMethod.Name = 'OnEntered') <CHECK THE EVENT NAME, THIS IS JUST AN EXAMPLE>
                CType(sender, Control).BackColor = Color.Yellow
                CType(sender, Control).ForeColor = Color.Black
      End IF
      IF(frame.GetMethod.Name = 'OnLeave')        
                CType(sender, Control).BackColor = Color.Black
                CType(sender, Control).ForeColor = Color.White
      End If
   NEXT --THIS NEEDS TO BE CHECKED, YOU MAY WANT TO EXIT BEFORE,ONCE FOUND YOUR EVENT.
 End Sub

还找到了前面提到的实际答案以示感谢。是How to get event name in vb.net?