【问题标题】:KeyDown Issue c#KeyDown 问题 c#
【发布时间】:2016-01-18 23:24:05
【问题描述】:

我目前正在尝试制作一个 keydown 寄存器。 基本上只是为了看看我最常使用哪些键。 问题是只希望它检测 F1-F12 按钮。 另一个问题是真的不知道如何攻击它,因为它必须是一个全局事件。

if (e.KeyCode.ToString() == "F1")
{
    MessageBox.Show("F1 pressed");
}

这是我迄今为止一直在尝试的,我确​​实必须专注于应用程序才能使其工作。

我不希望用户自己注册热键。 我想要他们设置,这就是这与Set global hotkeys using C#的不同之处

【问题讨论】:

  • 您希望它在全球范围内工作吗?我的意思是,在每个应用程序上,而不仅仅是你的?
  • 搜索低级键盘挂钩。在 codeproject 中也有一个解决方案。我想这就是你想要的。进入第一个搜索结果google.com/…
  • 我尝试用 ProcessCMDKey 代替它,它只在错误中解决:CS0161 'form1.ProcessCmdKey(ref Message, Keys)': Not all code paths return a value

标签: c# key keypress keydown keyup


【解决方案1】:

当我需要在 C# 中执行此操作时,我只需导入 User32.dll,并使用 GetASyncKeyState 函数如下:

[DllImport("User32.dll")]
private static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);

private void globalKeyThread()
{
   int state;
   System.Windows.Forms.Keys keyToCheck = Keys.Space;

   while (true)
   {
      state = Convert.ToInt32(GetAsyncKeyState(keyToCheck));

      if (state == -32767)
      {
         // Handle what happens when key is pressed.
      }

      Thread.Sleep(10);
   }
}

【讨论】:

  • 没有错误,当我使用它时,应用程序似乎没有得到我按空格键。
【解决方案2】:
private void globalKeyThread()
        {
            System.Windows.Forms.Keys keyToCheck = Keys.F12;

            while (true)
            {
                state = Convert.ToInt32(GetAsyncKeyState(keyToCheck));

                if (state == -32767)
                {
                    // Handle what happens when key is pressed.
                    timer1.Start();
                }

                Thread.Sleep(10);
            }
        }

这里的问题可能是 Int32 响应? 由于应用程序并没有真正理解我想要做什么。

【讨论】:

    【解决方案3】:
    using System.Runtime.InteropServices;
    

    导入 User32.dll:

    [DllImport("User32.dll")]
    private static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);
    

    下一个创建函数将检查按键是否被按下:

    private bool globalKeyThread(Keys key)
    {
        int state;
        state = Convert.ToInt32(GetAsyncKeyState(key));
        if (state == -32767)
        {
            return true;
        }
        return false;
    }
    

    现在定时器的功能只适用于F1:

    private void timer1_Tick(object sender, EventArgs e)
    {
        timer1.Enabled = false;
    
        if (globalKeyThread(Keys.F1))
        {
            MessageBox.Show("F1 press");
        }
        timer1.Enabled = true;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多