Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to handle all the number buttons in one keyboard event instead of doing for each buttons in a calculator?

Instead of copying and pasting for each number is there a method that could reference to all buttons?

private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.D5)
            {
                Five.PerformClick(); 
                    
            }
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.D5)
            {
                Five.PerformClick();
            }
        }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Firstly, the enum values Keys.D0 to Keys.D9 have sequential integer values. You can abuse this knowledge to turn the KeyCode directly into an array index.

var buttons = new Button[] {Zero, One, ... etc ...};
if(e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9){
    var index = (int)e.KeyCode - (int)Keys.D0;
    var button = buttons[index];
    button.PerformClick();
}
if(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9){
    // similar to the above
}

Or you could rearrange your code. Create a separate method for doing the work of "user entered a digit". Then call that method from both the button click event and form key event.

private void HandleDigit(int value){
    // todo
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9){
        var value = (int)e.KeyCode - (int)Keys.D0;
        HandleDigit(value);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading