Capturing Keypress Events in VB.NET [closed]
开发者_Python百科
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this questionI'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?
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
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
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
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.
精彩评论