Вопрос

The utility I am writing requires use of the SetWindowsHookEx function to capture key presses with the LowLevelKeyboardProc callback.

I have implemented the code found on this MSDN blog.

The correct keycode is being captured, however I appear to be unable to get the correct value of the 30th bit when using the bitmask taken from the answer to this StackOverflow question: Get 30th bit of the lParam param in WM_KEYDOWN message

private const int LAST_KEY_STATE_BITMASK = 0x40000000;

This bit should allow me to detect if the key is being held down, according to the Microsoft documentation.

I only want to act upon a keydown event when the key is first pressed and is not being held; keyup won't suffice.

The code I am using to try and get the value of the 30th bit is:

    int vkCode = Marshal.ReadInt32(lParam);
    int lastKeyState = (vkCode & LAST_KEY_STATE_BITMASK);

Which, from my understanding, should return 0 when the key isn't being held down and 1 when it is.

I have also tried using lParam.ToInt32() and (int)lParam in place of vkCode but to no avail.

Please help!

Here's the full program as it is in its current state:

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class KeyCapture
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private const int LAST_KEY_STATE_BITMASK = 0x40000000;

    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    public static void Main()
    {
        _hookID = SetHook(_proc);
        Application.Run();
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelKeyboardProc(
        int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            int lastKeyState = (vkCode & LAST_KEY_STATE_BITMASK);

            Console.WriteLine((Keys)vkCode + "|" + vkCode + "|" + lastKeyState);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook,
        LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
        IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);
}
Это было полезно?

Решение

As Igor kindly pointed out, I had to manage this myself.

The solution was simply a case of having a static list of ints for any key down that has been received without a key up event to follow.

private static readonly List<int> KeysDown = new List<int>();

private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0)
    {
        var keycode = Marshal.ReadInt32(lParam);

        if (wParam == (IntPtr)WM_KEYUP)
        {
            KeysDown.RemoveAll(k => k == keycode);
        }

        if (wParam == (IntPtr)WM_KEYDOWN)
        {
            if (!KeysDown.Contains(keycode))
            {
                // Do stuff!
            }

            KeysDown.Add(keycode);
        }

    }

    return CallNextHookEx(_hookId, nCode, wParam, lParam);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top