I'm trying to make a button that handles both enters and clicks. I've set up my sub procedure to handle both keyups and mouse clicks, however I cannot access MouseEventArgs from EventrArs nor KeyEventArgs from System.EventArgs. How can I do such?

有帮助吗?

解决方案

While your question isnt exactly clear, it sounds like you are trying to key keyboard events "from" System.EventArgs?

I'm not exactly sure what your asking, but posting code with your question would help us give accurate answers.

The following i assume I am guessing what you are asking is relevant to the sample below:

EventArgs is a type, it is also the base type for all events.

It seems you want a subroutine that can handle both Click and Keypresses in one go.

The following subroutine 'e_Handler' will accept MouseEventArgs, KeyEventArgs, and KeyPressEventArgs by checking the event type and casting it to a variable, in which u can then test or use the resulting states accordingly.:

' Handler for 3 event types:

Sub e_Handler(Sender As Object, E As EventArgs)

    If TypeOf E Is MouseEventArgs Then
        Dim K As MouseEventArgs = CTypeDynamic(Of MouseEventArgs)(E)

        MsgBox("Clicked Mouse at position " & K.Location.ToString & " on " & Sender.ToString)
    End If

    If TypeOf E Is KeyPressEventArgs Then
        Dim K As KeyPressEventArgs = CTypeDynamic(Of KeyPressEventArgs)(E)

        MsgBox("Pressed the key " & K.KeyChar & " on " & Sender.ToString)
    End If

    If TypeOf E Is KeyEventArgs Then
        Dim K As KeyEventArgs = CTypeDynamic(Of KeyEventArgs)(E)

        MsgBox("Pressed the key " & K.KeyCode & " on " & Sender.ToString)
    End If

    Me.Text = E.ToString

End Sub

You can then make this routine the handler for any number of events and controls:

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    AddHandler Me.MouseClick, AddressOf e_Handler
    AddHandler Me.KeyPress, AddressOf e_Handler
    AddHandler Me.KeyDown, AddressOf e_Handler


    For Each C As Control In Me.Controls
        AddHandler C.MouseClick, AddressOf e_Handler
        AddHandler C.KeyDown, AddressOf e_Handler
        AddHandler C.KeyPress, AddressOf e_Handler
    Next
End Sub

Edit:

The use of CTypeDynamic is to avoid compiler "implicit conversion" warnings, and ensures the method wont throw and exception if you set your project to compile with Option Strict

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top