Search code examples
c#keypress

Disable paste on a textbox via keypress


I've assigned the following method to all of my

    private void textBox18_KeyPress_1(object sender, KeyPressEventArgs e)
    {
        char a = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);


        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
          (e.KeyChar != a))
        {
            e.Handled = true;
        }

        // only allow one decimal point 
        if ((e.KeyChar == a) && ((sender as TextBox).Text.IndexOf(a) > -1))
        {
            e.Handled = true;
        }


    }

It basically allows one decimal separator (of any kind), and allows only numbers. I'd rather disable "paste" as well on this method. Is this possible?

I know some users might redirect me here

how to disable copy, Paste and delete features on a textbox using C#

But my code doesn't recognize e.Control and e.KeyCode. Even when I add using Windows.Forms at the form beginning. And even then, I wouldn't know if those solutions would work.


Solution

  • Those properties aren't available in the KeyPress event:

    The KeyPress event is not raised by non-character keys other than space and backspace; however, the non-character keys do raise the KeyDown and KeyUp events.

    Subscribe to the KeyDown event, where you have access to any modifier keys (control, alt, shift) the user happens to be pressing.

     private void textBox18_KeyDown(object sender, KeyEventArgs e)
     {
         if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V)
         {
             // cancel the "paste" function
             e.SuppressKeyPress = true;
         }
     }