简体   繁体   English

KeyDown 问题 c#

[英]KeyDown Issue c#

I'm currently trying to make a keydown register.我目前正在尝试制作一个 keydown 寄存器。 Basicly just to see which keys i use the most.基本上只是为了看看我最常使用哪些键。 The problem is that only want it to detect the F1-F12 buttons.问题是只希望它检测 F1-F12 按钮。 Another issue is don't really know how to attack it since it must be a globalevent.另一个问题是不知道如何攻击它,因为它必须是一个全局事件。

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

Is what I've been trying so far, I do have to focus the application for it to work tho.到目前为止,这是我一直在尝试的,我必须专注于应用程序才能正常工作。

I DO NOT want the user to register the hotkeys on their own.我不希望用户自己注册热键。 I want them set, that's what differs this from Set global hotkeys using C#我想设置它们,这与使用 C# 设置全局热键的不同之处

When I need to do this in C#, I just import User32.dll, and utilize the GetASyncKeyState function as follows:当我需要在 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);
   }
}
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);
            }
        }

The issue right here might be the Int32 response perhaps?这里的问题可能是 Int32 响应? Since the application is not really understanding what i'm trying to do.由于应用程序并没有真正理解我想要做什么。

using System.Runtime.InteropServices;

Import User32.dll:导入 User32.dll:

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

Next create function will check that key is pressed:下一个创建函数将检查是否按下了键:

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

Now function for timer is only for F1:现在计时器功能仅适用于 F1:

private void timer1_Tick(object sender, EventArgs e)
{
    timer1.Enabled = false;

    if (globalKeyThread(Keys.F1))
    {
        MessageBox.Show("F1 press");
    }
    timer1.Enabled = true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM