Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

c# - 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);
    }        
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...