如何识别键盘中的大小写字母?

时间:2018-09-10 15:18:26

标签: c# hook keyboard-hook

如何通过(Keys) Marshal.ReadInt32 (lParam) +选中Shift键同时捕获大键和小键。

我想学习如何捕获所有键盘键,但是我不知道如何正确地完成它。

public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
private static readonly LowLevelKeyboardProc _proc = HookCallback;

private static IntPtr _hookID = IntPtr.Zero;

private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
  if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
  {
    try
    {
       Console.WriteLine((Keys)Marshal.ReadInt32(lParam));
    }
    catch (AccessViolationException ex) { Console.WriteLine($"Error: {ex.ToString()}"); }
  }
  return NativeMethods.CallNextHookEx(_hookID, nCode, wParam, lParam);
}

很多事情是无法理解的。以及如何定义字符键?

是否可以将键转换为UnicodeEx?

1 个答案:

答案 0 :(得分:0)

检查我的键盘记录程序功能Here

您可能想要检查的功能:

private void Form1_Load(object sender, EventArgs e)
        {
            button2.Enabled = false;
            try {
                gHook = new GlobalKeyboardHook(); // Create a new GlobalKeyboardHook
                                                  // Declare a KeyDown Event
                gHook.KeyUp += new KeyEventHandler(gHook_KeyUp);
                gHook.KeyDown += new KeyEventHandler(gHook_KeyDown);
                // Add the keys you want to hook to the HookedKeys list
                foreach (Keys key in Enum.GetValues(typeof(Keys)))
                    gHook.HookedKeys.Add(key);
            }
            catch (Exception z)
            {

            }

        }

public void gHook_KeyDown(object sender, KeyEventArgs e)
        {

            String getCharVar = getCharDown(e.KeyValue);
           if(getCharVar!=null)
                richTextBox1.Text += getCharVar;

        }



private String getCharDown(int Value)
        {

            if (Value > 95 && Value < 106)
                return ((char)(Value-48)).ToString();

            if (Value > 64 && Value < 91)
            {if(!Control.IsKeyLocked(Keys.CapsLock))
                return ((char)(Value+32)).ToString();
            else
                    return ((char)(Value)).ToString();
            }
            if (Value > 47 && Value < 58)
                return ((char)Value).ToString();


            return null;
        }

PS::您可以重建项目以便进行测试。