Live Chat Icon For mobile
Live Chat Icon

How can I catch keyboard messages on a application-wide basis

Platform: WinForms| Category: Keyboard Handling

You can implement the IMessageFilter interface in your main form. This amounts to adding an override for PreFilterMessage, and looking for the particular message you need to catch. Here are code snippets that catch an escape key on a keydown. You can download a sample project(C#, VB). In the sample, there are two forms, with several controls. You’ll notice that no matter what form or control has input focus, the escape key is caught in the PreFilterMessage override.

[C#]
public class MyMainForm : System.Windows.Forms.Form, IMessageFilter
{
  const int WM_KEYDOWN = 0x100;
  const int WM_KEYUP = 0x101;

  public bool PreFilterMessage(ref Message m) 
  {
    Keys keyCode = (Keys)(int)m.WParam & Keys.KeyCode;
    if(m.Msg == WM_KEYDOWN  && keyCode == Keys.Escape)
    {
      Console.WriteLine(''Ignoring Escape...'');
      return true;
    }
    return false;
  }
  ....
  ....
  ....
  private void MyMainForm_Load(object sender, System.EventArgs e)
  {
    Application.AddMessageFilter(this);
  }
}

[VB.NET]
Public Class MyMainForm
  Inherits System.Windows.Forms.Form
  Implements IMessageFilter 

  Private WM_KEYDOWN As Integer = &H100
  Private WM_KEYUP As Integer = &H101

  Public Function PreFilterMessage(ByRef m As Message) As Boolean
    Dim keyCode As Keys = CType(CInt(m.WParam), Keys) And Keys.KeyCode
    If m.Msg = WM_KEYDOWN And keyCode = Keys.Escape Then
      Console.WriteLine(''Ignoring Escape...'')
      Return True
    End If
    Return False
  End Function ’PreFilterMessage
   ....
   ....
   ....
  Private Sub MyMainForm_Load(sender As Object, e As System.EventArgs)
    Application.AddMessageFilter(Me)
  End Sub ’MyMainForm_Load
End Class ’MyMainForm

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.