tags:

views:

364

answers:

4

I am using C#.Net. I have textbox which allow only number, decimal and percentage(%) sign. I have the keycode for all number and decimal, but what is the "%" sign's keycode?

How can I check the keydown event for %?

+9  A: 

Something like this:

private void yourControl_KeyDown(object sender, KeyEventArgs e)
{
   if((e.KeyCode == Keys.D5) && e.Shift)
   {
      // User pressed '%' ...
   }
}

or

private void yourControl_KeyDown(object sender, KeyEventArgs e)
{
    switch(e.KeyCode)
    {
        //... 
        case Keys.D5:
            if(e.Shift)
            {
                // Handle '%'
            }
            else
            {
                // Handle '5'
            }
            break;
        // ...
    }
}

You want to check that the key being pressed is the 5 key, and that it has been modified by pressing the shift key.

Daniel LeCheminant
how can i check with switch (e.KeyCode) { case Keys.Add: -- I need percentage sign to check
Kartik
can you please help me out in the case of if i compare in switch case
Kartik
what if the % sign isn't on shift+5? (e.g. french keyboard layout)
d0k
@d0k: Interesting point. Not sure how you'd handle it then :|
Daniel LeCheminant
btw, in russian % is shift+5 too. it's pity then in french not. it would be nice # and % to be always on the same button
abatishchev
Thanks lot.. it's working fine in English keyboard.. thanks for ur answer.
Kartik
It will not works if keyboard layout isn't english!
abatishchev
@abatishchev: I'll admit the solution isn't 100 shift+5 perfect...
Daniel LeCheminant
+2  A: 

Ascii code for "%" is 37, and in unicode &#37.

Harold
and KeyEventArgs.KeyValue is 53
abatishchev
A: 
private void control_KeyUp(object sender, KeyEventArgs e)
{
  if (e.KeyValue == 53)
  {
    // %
  }
}
abatishchev
A: 

Here is a textbox restricting pattern:

    private void AmountPaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        switch ((byte)e.KeyChar)
        {
            case 48:
            case 49:
            case 50:
            case 51:
            case 52:
            case 53:
            case 54:
            case 55:
            case 56:
            case 57:
            case 58:
            case 59:
            case 46:
            case 35:

                //This is a valid character
                e.Handled = false;
                break;
            default:
                //This is an invalid character
                e.Handled = true;
                break;

        }
    }
Gregory A Beamer
The original did not have case 35 in it, as I only allow numbers and decimals.
Gregory A Beamer
Oops, that should be case 37, per the ASCII chart (http://www.unitechnical.info/Products/ASCII-Chart.jpg). Ouch!
Gregory A Beamer