I strongly suggest you pick up a copy of a C# book (covering Windows Forms, etc) or try to follow an on-line tutorial.
For example, take a look at this tutorial or this one... Googling "C# windows forms calculator" gives 320,000 hits!
On-keys screen
Assuming you are developing a GUI and by 'key-presses' you mean the 'on-screen keys', then what you are wanting to do, roughly, is:
- Assign an event to your button, the Click event seems best.
- In the event-handler, you will need to maintain some list of clicks or convert directly to a number e.g. currentDisplayValue = (currentDisplayValue * 10) + thisDigit
- When the plus, minus, multiply, divide, equals buttons are pressed, you need to do the appropriate action with the displayValue and the previously calculated value.
The logic of a calculator will be easy to find on the internet, the magic is wiring the button's events to an event handler to do the work for you!
Physical keys (eg. number-pad)
This gets harder. The GUI typically routes the keyboard to the focused control. You need to overcome this routing:
- On the form, set
KeyPreview
to true
Register an event-handler to the form
// Associate the event-handling method with the
// KeyDown event.
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
In the event-handler, do your calculation using the "KeyCode" values
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case "0":
// Zero
break;
case "1":
// One
break;
// .. etc
case "+":
// Plus
break;
default:
// Avoid setting e.Handled to
return;
}
e.Handled = true;
}