Reputation: 21
I am making a messenger application using winForms. So when I type a message in the sender's text box and press enter, the message gets delivered but the cursor on my text box automatically goes to the next line for the first time. And then it stays there for all the messages I type and send. I am using a simple keypress event for enter button which uses return. What can the problem be? The code is as follows:
private void txtChatOperatorMsg_KeyPress (object sender, KeyPressEventArgs e) {
if (e.KeyChar == (char) Keys.Return) {
pushToClientAndEmpty (txtChatOperatorMsg.Text);
}
}
private void pushToClientAndEmpty (string message) {
operatorgetset = message;
Thread operatorChatThread = new Thread (new ThreadStart (newThreadOperatorChat));
operatorChatThread.Start ();
txtChatOperatorMsg.Clear();
}
string operatorgetset {get;set;}
private void newThreadOperatorChat () {
SetText (operatorgetset);
}
Upvotes: 0
Views: 410
Reputation: 2142
This is what will work for you:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != 13) return;
textBox.Clear();
e.Handled = true;
}
As Binkam suggested, the key thing is e.Handled
.
Upvotes: 0
Reputation: 3048
Have you tried to set KeyPressEventArgs.Handled to true
? This marks the event as handled and further processing is skipped. In order to work, your EventHandler
needs to come prior the internal one.
Upvotes: 1