I've searched all over and can not find an example of this
in C#. Does anyone know how to do this?
Thanks,
Eric
There isn't a class to do this out of the box. In order to do this, you
will have to make a call to the SetWindowsHookEx API function through the
P/Invoke layer. You will want to pass the WH_KEYBOARD flag in to monitor
keyboard events.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- nicholas...@exisconsulting.com
"Eric J Campbell" <eric_j_...@dell.com> wrote in message
news:031401c2fe0f$aeda45a0$a101...@phx.gbl...
"Eric J Campbell" <eric_j_...@dell.com> wrote in message
news:031401c2fe0f$aeda45a0$a101...@phx.gbl...
As Nicholas mentions, one way to do this would be to use SetWindowsHookEx to
insert a hook for keyboard events; however, this tends to slow down
performance since you're now running your code every time a key is pressed.
A different approach is to use the WinAPI call RegisterHotKey (and
UnRegisterHotKey).
For example:
[Flags]
public enum FSMODIFIERS: uint
{
MOD_ALT = 0x0001,
MOD_CONTROL = 0x0002,
MOD_SHIFT = 0x0004,
MOD_WIN = 0x0008
};
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, FSMODIFIERS
fsModifiers, Keys virtualKey);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
You'll notice that RegisterHotKey takes a window handle - it uses this to
post a message to your window any time that hot-key is pressed (the Keys
enumeration used in the declaration of RegisterHotKey is from
System.Windows.Forms).
A call to RegisterHotKey would look like this:
if (RegisterHotKey(this.Handle, 20, FSMODIFIERS.MOD_WIN, Keys.D1))
{
MessageBox.Show("Success!");
}
else
MessageBox.Show("Failure!");
Which would register a hotkey for windows+1. Remember to call
"UnregisterHotKey" when your application is closing. RegisterHotKey can
fail if that hot-key is already registered by a different program.
Of course, now you have to handle that windows message... so... you'll have
to override your WndProc. You could do something like this:
const int WM_HOTKEY = 0x0312;
protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case WM_HOTKEY:
this.Activate();
break;
default:
base.WndProc(ref m);
break;
}
}
This would cause your form to be shown any time that hot-key is pressed.
Hope this helps,
Anson
--
This posting is provided "AS IS" with no warranties, and confers no rights
"Eric J Campbell" <eric_j_...@dell.com> wrote in message
news:031401c2fe0f$aeda45a0$a101...@phx.gbl...