How to implement listener for F7 key

  • Thread starter Thread starter Roger
  • Start date Start date
R

Roger

I have an application that I want to run in the background until F7 key is
pressed. Does anyone know how to implement a listener for F7 keypress to
activate application?
 
Hello Roger,
I have an application that I want to run in the background until F7 key is
pressed. Does anyone know how to implement a listener for F7 keypress to
activate application?

This can be made with a global system (keyboard) hook:

[Global System Hooks in .NET]
http://www.codeproject.com/csharp/GlobalSystemHook.asp

[Windows Hooks in the .NET Framework]
http://msdn.microsoft.com/msdnmag/issues/02/10/CuttingEdge/

[Using Windows Hooks to Enhance MessageBox in .NET]
http://msdn.microsoft.com/msdnmag/issues/02/11/CuttingEdge/


ciao Frank
 
Roger said:
I have an application that I want to run in the background until F7 key is
pressed. Does anyone know how to implement a listener for F7 keypress to
activate application?

win32 api has a RegisterHotKey, to listen for CTRL+ALT+SHIFT+D:

internal class Win32
{
[DllImport("user32.dll", SetLastError=true)]
public static extern bool RegisterHotKey(IntPtr hWnd, int
hotkeyId, KeyModifiers fsModifiers, Keys vk);
[DllImport("user32.dll", SetLastError=true)]
public static extern bool UnregisterHotKey(IntPtr hWnd, int hotkeyId);
[Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Windows = 8
}
}

public class SomeForm {
...
protected int hotkeyid = SOME_INTEGER_ID;
protected bool hotkey_registered;
SomeForm()
{
hotkey_registered = Win32.RegisterHotKey(Handle, hotkeyid,
Win32.KeyModifiers.Control | Win32.KeyModifiers.Alt |
Win32.KeyModifiers.Shift, Keys.D);
}
protected override void Dispose( bool disposing ) {
if ( hotkey_registered )
Win32.UnregisterHotKey(Handle, hotkeyid);
...
}

protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
switch(m.Msg)
{
case WM_HOTKEY:
hotkeyPressed(ref m);
break;
}
base.WndProc(ref m );
}
public void hotkeyPressed(ref Message m) { ... }
}

In the docs for RegisterHotKey the following is said of hotkeyid:

"[in] Specifies the identifier of the hot key. No other hot key in the
calling thread should have the same identifier. An application must
specify a value in the range 0x0000 through 0xBFFF. A shared
dynamic-link library (DLL) must specify a value in the range 0xC000
through 0xFFFF (the range returned by the GlobalAddAtom function). To
avoid conflicts with hot-key identifiers defined by other shared DLLs, a
DLL should use the GlobalAddAtom function to obtain the hot-key
identifier. "
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top