-1

I'm feeling frustrated. I have spent hours looking for a good piece of code to capture the keypress events in any windows no matter if my application is focused or not. I need to create an application to work in the background to capture the F5 key. Does anyone have any code?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Logan
  • 31
  • 1
  • 2
  • 6

4 Answers4

1

I know this is all C# and OP asked about VB.Net, but the concepts are the same...

I wrote a simple utility that handled global key presses using this project. Download the library, and add a reference to it in your project, and import the Gma.UserActivityMonitor namespace

In your form load event, add the handlers.

HookManager.KeyDown += KeyDown;
HookManager.KeyUp += KeyUp;

In these methods, I'm looking for either control key to be pressed.

void KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.LControlKey || e.KeyCode == Keys.RControlKey)
    {
        //Do Stuff
    }
}
void KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.LControlKey || e.KeyCode == Keys.RControlKey)
    {
        //Do Stuff
    }
}

With the way this is written, the key press will still be available to other apps to process. If you want to "capture" the key and halt its processing by other apps, set the Handled property to true in your event handler.

e.Handled = true;

EDIT: Conversion of above code to VB.Net

To add handlers in VB.Net, you use AddHandler and AddressOf.

AddHandler HookManager.KeyDown AddressOf KeyDown

The functions KeyDown and KeyUp would look like this.

Sub KeyDown(ByVal sender as Object, ByVal e as KeyEventArgs)
    If e.KeyCode = Keys.LControlKey Or e.KeyCode = Keys.RControlKey Then
        'Do Stuff
    End If
End Sub
Tim Coker
  • 6,484
  • 2
  • 31
  • 62
  • I am really new to VB.NET, is there any way that you could give me an answer in raw, simple VB.NET? – Logan Jul 06 '11 at 14:34
0

You have to use Form keypress event...on which form you want to capture F5 keypress event.

Check this: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.71).aspx

Ovais Khatri
  • 3,201
  • 16
  • 14
0

In order to capture key press events when a form does not have focus you would need to get into some pretty low level stuff. Global keyboard hooks are usually not possible in C# or VB.NET, but here's an article that might help you:

Managing Low-Level Keyboard Hooks in VB .NET

*make sure to also check out Lucianovici's notes in the comments below the article

diceguyd30
  • 2,742
  • 20
  • 18
0

There is a duplicate of this topic, which I answered with a VB.NET solution in detail. It uses the same Hook Library that Tim Coker suggested.

Community
  • 1
  • 1
David Anderson
  • 13,558
  • 5
  • 50
  • 76