Capture keystrokes (e.g., function keys) while a messagebox is up

Posted by FastAl on Stack Overflow See other posts from Stack Overflow or by FastAl
Published on 2010-06-15T19:59:18Z Indexed on 2010/06/15 20:02 UTC
Read the original article Hit count: 572

Filed under:
|
|
|

We have a large WinForms app, and there is a built-in bug reporting system that can be activated during testing via the F5 Key. I am capturing the F5 key with .Net's PreFilterMessage system. This works fine on the main forms, modal dialog boxes, etc.

Unfortunately, the program also displays windows messageboxes when it needs to. When there is a bug with that, e.g., wrong text in the messagebox or it shouldn't be there, the messagefilter isn't executed at all when the messagebox is up!

I realize I could fix it by either rewriting my own messagebox routine, or kicking off a separate thread that polls GetAsyncKeyState and calls the error reporter from there. However I was hoping for a method that was less of a hack. Here's code that manifests the problem:

Public Class Form1 
    Implements IMessageFilter

Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
    MsgBox("now, a messagebox is up!")
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Application.AddMessageFilter(Me)
End Sub

Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) _
 As Boolean Implements IMessageFilter.PreFilterMessage

    Const VK_F5 As Int32 = &H74
    Const WM_KEYDOWN As Integer = &H100

    If m.Msg = WM_KEYDOWN And m.WParam.ToInt32 = VK_F5 Then
        ' In reality code here takes a screenshot, saves the program state, and shows a bug report interface '
        IO.File.AppendAllText("c:\bugs.txt", InputBox("Describe the bug:"))
    End If

End Function
End Class

Many thanks.

© Stack Overflow or respective owner

Related posts about c#

Related posts about vb.net