Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
Dear Friends,

I have prepared a calculator in C#. Every thing is working fine, but I want to do something new i.e. when the user press a key from keyboard the event related to it should get activated. for eg: if user presses number 1 from numerical keypad then in textbox value should be 1 and the value 1 comes but then again textbox should be activated and if the user press plus key on keyboard then the add button click event should get activated, but what actually happens is that + sign appears in textbox, this should not happen.

Every time the user presses any key on the keyboard, the control should get transfered to the textbox. Please Can Anybody help ???

Thanks in Advance !!!
Posted

I assume you are have a WinForms application? I would likely use the OnKeyPress even to do what you want, but the OnKeyUp or OnKeyDown events might be better for your specific case.
 
Share this answer
 
v2
Comments
Sander Rossel 4-Nov-11 17:24pm    
My 5. I'd do the same :)
Ok so Solution 1 handles the key press and as far as not displaying the plus sign in the text box you will need to do something like this in your KeyDown or KeyUp event handler:

C#
if (e.KeyCode == Keys.Add || e.KeyCode == Keys.Oemplus)
{
    //do not add this to the text box
}
 
Share this answer
 
v2
Comments
Sander Rossel 4-Nov-11 17:24pm    
My 5. Good addition to Walt's answer.
The two above answers are both correct. However, I would like to point you on a little detail that I have often overlooked myself. When you want your Form to raise the KeyDown, KeyUp, KeyPress Events you should make sure the KeyPreview Property[^] of your Form is set to true. Your Form will then get ALL key presses you make (also key presses you make in Controls on your Form).
Another read you might be interested in is How Programming Should Be Done[^] by Marc Clifton. Compare it to your own calculator and see where your two are different. Could be a great way to see how things could be done differently :)
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 4-Nov-11 20:42pm    
Good point, my 5. Actually, without this detail OP could have a lot of frustration instead of the solution :-).
--SA
Sander Rossel 5-Nov-11 4:58am    
Thanks. This was the first thing that came to mind, since I've forgotten it myself many times ;p

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900