i made a basic calculator. but i don't know how to assign keypress. how it assigned?
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
totrue
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; }
If this calculator is windows forms application then:
just double click on the buttons in designer (visual studio designer where you created form and added buttons to it). This will add click handlers for your buttons.
for keypress select button, now in properties tab click on the lightening bolt icon (for showing events instead of properties in grid) and double click KeyPress event.
If you mean assigning shortcut keys then simply add & before button text like (&8), then user will be able to press Alt+8 to simulate clicking of 8 button.
Assuming that you have buttons for numbers and mathematical operations, you may also do the following:
- Set the form's
KeyPreview
property totrue
- Add an
OnKeyPress
event handler to the form - Handle any key necessary
The code to handle the key press could look like:
if (e.KeyChar == '0')
{
e.Handled = true;
btn0.PerformClick();
}
That means: If the '0'-Key is pressed, programmatically push the button that stands for 0
. You can handle *
, /
etc. in the same way.
EDIT
Of course I assume that you have assigned a click event to the respective buttons that already do what you want to do (e.g. add number to display, perform operation on numbers and display result, etc.).