Question How do I use the number pad to enter numbers into a textbox?

MinusZero

Member
Joined
Oct 22, 2012
Messages
7
Programming Experience
1-3
I am learning C# and am making a calculator. All is going well so far except its driving me mad trying to make it accept keyboard commands.

I have done some testing in another file and can simply add keyboard commands to a textbox or label using the code below in the KeyPress event:

C#:
textbox1.Text += e.KeyChar;

However, for the purposes of a calculator, being able to add all keyboard characters isnt ideal.

I have searched many forums and have seen code like:

C#:
if (e.KeyCode == Keys.Numpad1)
{
    Entercode here
}

But when i try to add e.KeyCode, KeyCode is not an option. Only KeyChar is, which doesnt work.

Anyone know why I cant have KeyCode?

Basically, I trying to write code that adds a numpad keypress to a textbox on a winform.

Thanks
 
KeyChar is a property of the KeyPressEventArgs class, which is what's received by the KeyPress event handler. KeyCode is a property of the KeyEventArgs class, which is received by various event handlers, most notably for you, KeyDown. You might like to follow the Blog link in my signature and check out my post on Keyboard Events for some useful information on the subject.
 
Thanks

Thanks heaps. I have been able to capture keys for my calculator project. I put the keypress event on the textbox. I have to also consider the focus, if a click is used on the screen, the focus moves from the textbox to the button and it can no longer accept keystrokes. Have fixed that though.

I was able to create the code using "if" or "switch".

Thanks!!! This was driving me mad.
 
Back
Top Bottom