Visual-Vincent / InputHelper

A .NET friendly library for simulating mouse and keyboard input.
BSD 3-Clause "New" or "Revised" License
13 stars 6 forks source link

Hooks aren't disposed together with the form they're in #2

Open Visual-Vincent opened 5 years ago

Visual-Vincent commented 5 years ago

When instantiating a hook in a form the hook is not disposed together with the form when the form is closed.

Steps to reproduce

  1. Create two forms.
  2. Make one form open the other (for instance via a button click).
  3. Put a keyboard and/or mouse hook in the second form.
  4. Use the mouse/keyboard hook.
  5. Close the second form.
  6. Try to use the mouse/keyboard hook again.
  7. It still works!

Code

Form1:

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Using form2 As New Form2
            form2.ShowDialog()
        End Using
    End Sub
End Class

Form2:

Public Class Form2

    Dim KeyboardHook As New InputHelper.Hooks.KeyboardHook

    Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        AddHandler KeyboardHook.KeyDown, AddressOf KeyboardHook_KeyDown
    End Sub

    Private Sub KeyboardHook_KeyDown(sender As Object, e As InputHelper.EventArgs.KeyboardHookEventArgs)
        If e.Modifiers = (InputHelper.ModifierKeys.Control Or InputHelper.ModifierKeys.Shift) AndAlso e.KeyCode = Keys.E Then
            Debug.WriteLine("'CTRL + SHIFT + E' pressed at " & DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
        End If
    End Sub
End Class

Result

(Immediate Window, Visual Studio)

(Form2 opened by Form1)
(User presses CTRL + SHIFT + E)

'CTRL + SHIFT + E' pressed at 2019-08-17 02:26:49

(Form2 closed)
(User presses CTRL + SHIFT + E again)

'CTRL + SHIFT + E' pressed at 2019-08-17 02:27:03