如何抑制键盘输入

时间:2015-05-17 19:28:00

标签: c# input

所以我试图制作一个程序来禁用所有键盘输入但仍能检测到按键的时间(无关紧要)。

我尝试使用BlockInput方法,但它阻止了所有输入(鼠标和键盘),并且不允许进一步检测键盘按下。

这是我当前的代码(函数是一个具有1个滴答间隔的计时器)

private void detect_key_press_Tick(object sender, EventArgs e)
    {
        Process p = Process.GetCurrentProcess();
        if (p != null)
        {
            IntPtr h = p.MainWindowHandle;
            //SetForegroundWindow(h);
            if (Keyboard.IsKeyDown(Key.A))
            {
                //SendKeys.SendWait("k");
                this.BackColor = Color.Red;

            }
            else
            {
                this.BackColor = Control.DefaultBackColor;
            }
        }
    }

我该怎么办?感谢。

修改

我试过

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        e.Handled = true;
        e.SuppressKeyPress = true;
    }

但没有成功。钥匙仍然可以被处理。

1 个答案:

答案 0 :(得分:1)

我假设您使用Windows窗体?

如果您将表单上的KeyPreview设置为true并在表单的KeyDown上创建一个事件,则可以通过该方式处理键盘输入。

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyData == Keys.S) // some accepted key
    //Do something with it
  else 
  {
    //or cancel the key entry
    e.Handled = true;
    e.SuppressKeyPress = true;
  }
}
相关问题