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.
Asked
Active
Viewed 2.0k times
0
-
5Metro? WinForms? WPF? Silverlight? Windows Phone? ASP.Net? MonoTouch? – SLaks Aug 07 '13 at 17:53
-
Have your method be executed by a Click method only? – Brock Hensley Aug 07 '13 at 17:55
-
1Do you have any code to show what you have tried? – Karl Anderson Aug 07 '13 at 17:56
-
textBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);"); – user2650977 Aug 07 '13 at 18:00
-
the goal is, if the Enter key is pressed to send the message, not go to a new line? – Jonesopolis Aug 07 '13 at 18:08
-
Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – John Saunders Aug 07 '13 at 18:11
3 Answers
4
You can try something like this:-
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
}

Rahul Tripathi
- 168,305
- 31
- 280
- 331
-
But the user still can press Enter key to sending the text from text box. Can disable the Enter key? – user2650977 Aug 07 '13 at 18:01
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;
}
}
-
3This 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