0

I am developing a chatting system. And I have a Button to send the text in the text box to the chat log. How am I going to stop the user from press Enter key and to disable the Enter key. I know there are many posts out there like this, but the solutions haven't worked for me.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user2650977
  • 103
  • 2
  • 2
  • 4

3 Answers3

4

You can try something like this:-

if (e.KeyCode == Keys.Enter) 
{
    e.SuppressKeyPress = true;
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
4

I think you do not need to stop the user from pressing enter but instead send the chat to the other person on press of enter.

Also if you have any other shortcuts to be allowed then you can have a look at this C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

Using the same you can also block

private void textBoxToSubmit_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.SuppressKeyPress=true;
    }
}
Community
  • 1
  • 1
puneet
  • 769
  • 1
  • 9
  • 34
  • 3
    This does not work on textbox in vb net 2015... it works for ANY key except Enter... I don't know why. – Zibri Nov 07 '16 at 11:19
1

Your question is a little ambiguous to say the least; however, the textbox control has an event called KeyDown : http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx

This way, you can capture whenever Enter is pressed and modify and behavior as needed, here is an example

private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (Keys.Enter == e.KeyCode)
        {
            MessageBox.Show("Enter Was Pressed");
            textBox1.Text = new String(textBox1.Text.Where((ch, i) => i < textBox1.Text.Length - 2).ToArray());
            textBox1.SelectionStart = textBox1.Text.Length;
        }
    }
Aelphaeis
  • 2,593
  • 3
  • 24
  • 42