Search code examples
c#.netkeypress

Detecting ctrl+v on key press


I am using text box keypress event to handle only selected inputs. Basically the textbox allow user to input values where it can be calculated.

i.e. you can type (5*5)- (10/5).

The current method check like Convert.ToChar("*")==e.KeyChar etc...

At the moment it doesn't allow user to copy paste values.

Is there anyway that can detect the ctrl+v on keypress event?

Update

What I am doing at the moment

   static IEnumerable<char> ValidFiancialCharacters
       {
           get
           {
               if(_validFiancialCharacters==null)
               {
                 _validFiancialCharacters = new List<char>();

                 _validFiancialCharacters.Add(Convert.ToChar("0"));
                 _validFiancialCharacters.Add(Convert.ToChar("1"));
                 _validFiancialCharacters.Add(Convert.ToChar("2"));
                 // till 9 and
                  _validFiancialCharacters.Add(Convert.ToChar("+"));
                  _validFiancialCharacters.Add(Convert.ToChar("-"));
                  _validFiancialCharacters.Add(Convert.ToChar("/"));
                  //and some other
                }
                return _validFiancialCharacters;
             }
       }


 public static bool ValidateInput(KeyPressEventArgs e)
   {
       if (ValidFiancialCharacters.Any(chr => chr == e.KeyChar))
       {
           e.Handled = false;
       }
       else
       {
           e.Handled = true;
       }
       return e.Handled;
   }

And in the keypress

   private void txtRate_KeyPress(object sender, KeyPressEventArgs e)
    {
        NumberExtension.ValidateInput(e);
    }        

Solution

  • If you need to handle both, can be done using the similar approach

    Have a look at Key Codes. You can detect what ever the key been pressed

    so..

    Create a list containing all the inputs you need

     public List<int> KeyCodes = new List<int>() { 8, 17, 37, 39.....etc}; 
    

    and use the KeyDown event and use KeyEventArgs.SuppressKeyPress property

    private void Txt1_KeyDown(object sender, KeyEventArgs e)
    {
        if (KeyCodes.Contains(e.KeyValue) || (e.KeyCode==Keys.V && e.Control))
            e.SuppressKeyPress = false;
        else 
            e.SuppressKeyPress=true;
    }
    

    You might need to validate the copy pasted value in leave event, since user can paste anything!!!