简体   繁体   中英

KeyDown Issue c#

I'm currently trying to make a keydown register. Basicly just to see which keys i use the most. The problem is that only want it to detect the F1-F12 buttons. 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#

When I need to do this in C#, I just import User32.dll, and utilize the GetASyncKeyState function as follows:

[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? Since the application is not really understanding what i'm trying to do.

using System.Runtime.InteropServices;

Import 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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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