Recommand · October 22, 2021 0

C# Custom User Keybinds

I would like to add custom Keybinds so if the user presses that Key it will execute a Function.

Therefore the user has to select a custom keybind first, I don’t want static predefined Keybinds, I want the user to be able to choose one.

I am using the following Code for that but it has some bugs in it and I would like to know if there is an easier and faster way to do that? (Without using the Form Keypress Event):

private void button1_Click(object sender, EventArgs e)
    {
        test();
    }

    [DllImport("user32.dll")]
    static extern short GetAsyncKeyState(Int32 i);

    private void test()
    {
        int keyState = 0;
        string test = "Press Key Now!";
        label1.Text = "Press Key Now!";
        Application.DoEvents();

        for(int i = 0; i < 255; i++)
        {
             keyState = GetAsyncKeyState(i);
                
            if (keyState == 1 || keyState == -32767)
            {
                label1.Text = Convert.ToString(((char)i));
                break;
            }   
        }
    }