问题
I want to be able to detect when the user presses F10 or Ctrl+F10 outside of my program, and upon receiving the key press, it will send text to whatever they currently have selected (e.g. a text box). How can this be accomplished in the simplest way?
回答1:
Use RegisterHotkey and not a keyboard hook to get a global hotkey.
See one of my older answers on almost the same question: listen for a key when the application is not focused
回答2:
The first problem here is that the F10 key is already a reserved key for Windows applications. When the user presses it, the active application selects the first menu in its menu bar. This provides a convenient way for users to activate menus without having to use their mouse. Your proposal to hijack that functionality globally is inconsiderate and inappropriate. I suggest choosing a different shortcut key, preferably one that doesn't already have a standard meaning.
Then, you will have to install a low-level keyboard hook (the only type of hook supported by .NET apps). This is the only way to capture keyboard events that occur outside of your application. Since you want to detect keypresses that occur when your application is not in the foreground, you'll need a global hook.
There's an excellent sample available here on Stephen Toub's blog. It happens to be written in C#, but converting to VB.NET is trivial. If you prefer a full base of existing code that you can simply add to your project, you can try this sample, but note that it includes a lot of additional functionality you won't need.
回答3:
You can check that in the keypress event:
if not e.control and e.keycode = keys.F10 then
<Statements>
elseif e.keycode = keys.F10 then
<Statements>
end if
来源:https://stackoverflow.com/questions/5216222/vb-net-detecting-keypress-while-minimized