Answer the question
In order to leave comments, you need to log in
How to configure hook on keyboard shortcut in C# [Solved]?
There is a program. Hook catches a key and performs a certain action. But she only catches one key. And I would like to set up a keyboard shortcut. Help, good people. :)
Hook code:
public class Hook : IDisposable
{
#region Declare WinAPI functions
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, KeyboardHookProc callback, IntPtr hInstance, uint threadId);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, int wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool UnhookWindowsHookEx(IntPtr hInstance);
#endregion
#region Constants
private const int WH_KEYBOARD_LL = 13;
private const int WH_KEYDOWN = 0x0100;
#endregion
// код клавиши на которую ставим хук
private int _key;
public event KeyPressEventHandler KeyPressed;
private delegate IntPtr KeyboardHookProc(int code, IntPtr wParam, IntPtr lParam);
private KeyboardHookProc _proc;
private IntPtr _hHook = IntPtr.Zero;
public Hook(int keyCode)
{
_key = keyCode;
_proc = HookProc;
}
public void SetHook()
{
var hInstance = LoadLibrary("User32");
_hHook = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, hInstance, 0);
}
public void Dispose()
{
UnHook();
}
public void UnHook()
{
UnhookWindowsHookEx(_hHook);
}
private IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam)
{
if ((code >= 0 && wParam == (IntPtr)WH_KEYDOWN) && Marshal.ReadInt32(lParam) == _key)
{
// бросаем событие
if (KeyPressed != null)
{
KeyPressed(this, new KeyPressEventArgs(Convert.ToChar(code)));
}
}
// пробрасываем хук дальше
return CallNextHookEx(_hHook, code, (int)wParam, lParam);
}
}
// 0x70 клавиша F1
_hook_F1 = new Hook(0x70);
_hook_F1.KeyPressed += new KeyPressEventHandler(_hook_F1_KeyPressed);
_hook_F1.SetHook();
void _hook_F1_KeyPressed(object sender, KeyPressEventArgs e) //Событие нажатия клавиш
{
//Нужное мне событие
}
Answer the question
In order to leave comments, you need to log in
UPD: Figured it out myself. When processing HookProc, it is necessary to compare wParam with 257 (combination with Ctrl) or 261 (combination with Alt)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question