I am developing a plugin for an application. I need to implement a low-level keyhook to capture keys. I have tried running the keyhook on the same thread as the main application + plugin, but it's performance is hit and miss. I'm not able to query this with the application's original developer.
Thus, I've implemented the code below to run the keyhook on a backgroundworker. It works reliably, but I'm very conscious of the Application.DoEvents
I understand this is bad. The code:
Private WithEvents KeyHookBGW As New BackgroundWorker
Private WithEvents KeyHook As New WindowsHookLib.KeyboardHook
Private Sub KeyHookBGW_DoWork(sender As Object, e As DoWorkEventArgs) Handles KeyHookBGW.DoWork
Dim BgKeyhook As New KeyboardHook
BgKeyhook.InstallHook()
AddHandler BgKeyhook.KeyDown, AddressOf KeyHookBGW_KeyDown
Do While e.Cancel = False
Application.DoEvents()
Loop
End Sub
Private Sub KeyHookBGW_KeyDown(sender As Object, e As WindowsHookLib.KeyboardEventArgs)
KeyHookBGW.ReportProgress(0, e.KeyCode)
End Sub
Private Sub KeyHookBGW_ReportProg(sender As Object, e As ProgressChangedEventArgs) Handles KeyHookBGW.ProgressChanged
pm.Console.WriteLine("Key pressed: " & e.UserState)
End Sub
I'm sure my architecture is bad, but I'm a bit stuck with getting this to work in the development context. I tried using a timer in the background thread, but couldn't get this to work. I'm also developing in .net Framework 3.5 (original application's framework) and thus this limits what I can do with Threads, I think. I've looked into Threads and I am struggling to understand how to run them infinitely and also communicate back to the main thread.
So, basically, I'm needing to run the keyhook on a separate thread for the lifetime of the main application + plugin and feed back any keydown and keyup events into the main thread. Any ideas?