-1

我想将按钮单击事件发送到文本框 keypressevent。该怎么办??

我的代码是

Private Sub TextBox1_KeyPress(ByVal sender As Object, _ 
       ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    MessageBox.Show "Hai"
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click

   TextBox1_KeyPress(Sender,e)

End Sub

错误来自 e

System.EventArgs 和 KeyPressEventArgs

4

1 回答 1

3

我认为以这种方式直接调用事件处理程序总是一种不好的方法。

在我看来,您应该重构代码并从 KeyPress 事件中提取要从 Button_Click 调用的代码并直接调用它

Private Sub TextBox1_KeyPress(ByVal sender As Object, _ 
       ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    CommonCode()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click

    CommonCode()
End Sub


Private Sub CommonCode()
    MessageBox.Show "Hai"
End Sub

但是,您的错误在于TextBox1_KeyPress期望在 Button1_Click 中接收到的KeyPressEventArgs不是简单的事实。EventArgs你可以绕过这个创建一个新实例KeyPressEventArgs并将其传递给TextBox1_KeyPress,但是,正如我所说,这是一个不好的做法。甚至不要认为 Windows 或框架会以某种有意义的方式处理对并非源自其内部代码的事件的调用。

编辑:只是为了展示如何传递 KeyEventArgs 的实例。我再次不推荐这个。

Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click

    Dim x = new KeyPressEventArgs("A"c)
    CommonCode(e, x)
End Sub

Private Sub CommonCode(ByVal sender As Object, ByVal e KeyPressEventArgs)

    MessageBox.Show "KeyPressed = " + e.KeyChar.ToString
End Sub
于 2013-01-20T10:58:38.707 回答