keydown in c# doesn't work for some reason

前端 未结 1 1571
温柔的废话
温柔的废话 2020-12-07 03:02

I\'m trying to do a calculator and all I have to do is make it work with the keyboard. This should work but it doesn\'t.

    private void Form1_KeyDown(objec         


        
相关标签:
1条回答
  • 2020-12-07 03:40

    Assuming you have a WinForms project, set the KeyPreview property of your form to true, like that (e.g. in the constructor) :

    public Form1()
    {
        InitializeComponent();
        KeyPreview = true;
    }
    

    and it should work like you expected.

    Edit: Due to your comment I've added the code to catch all the signs (add that to your Form1_KeyDown method)

    if (((e.KeyCode == Keys.D7) && (e.Modifiers == Keys.Shift)) || (e.KeyCode == Keys.Divide))
    {
        sign("/");
    }
    else if (((e.KeyCode == Keys.Oemplus) && (e.Modifiers == Keys.Shift)) || (e.KeyCode == Keys.Multiply))
    {
        sign("*");
    }
    else if ((e.KeyCode == Keys.OemMinus) || (e.KeyCode == Keys.Subtract))
    {
        sign("-");
    } 
    else if ((e.KeyCode == Keys.Oemplus) || (e.KeyCode == Keys.Add))
    {
        sign("+");
    } 
    else if (e.KeyCode == Keys.Enter)
    {
        sign("=");
    }
    
    0 讨论(0)
提交回复
热议问题