user607455
user607455

Reputation: 479

C# Textbox starts on second line after pressing Enter

After my textbox clears. The start position starts at second line instead of the first. (I'm not sure what's the flashing | is called)

I'm making a chat server so there is a button to send the current text. And on keypress Enter it will activate button1 so as to send the current text.

TextChanged event is just purely for debugging purposes.

textChanged is called twice. Once on inBox.Text = string.Empty; This part is still fine. inBox.Text is null.

After exiting from button1_Click, TextChanged is called for the second time. But this time. the start position is on the second line instead of the first. The length of inBox.Text is now 2.

Any idea what's the problem? Thanks.

private void button1_Click(object sender, EventArgs e)
        {
            Global.Send("{Chat}{" + Global.userName + "}" + inBox.Text);
            inBox.Text = string.Empty;
        }

        private void inBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                button1.PerformClick();
        }

        void InBoxTextChanged(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            char[] c = tb.Text.ToCharArray();
            int len = c.Length;
        }

Upvotes: 0

Views: 1297

Answers (3)

Ken White
Ken White

Reputation: 125748

In the Inbox_Keypressed() method, set the KeyPressEventArgs.Handled property to true (also, you shouldn't use 13 - Keys.Return is more readable):

private void inBox_KeyPress(object sender, KeyPressEventArgs e)
{
  if (e.KeyChar == 13)
  {
    button1.PerformClick();
    e.Handled = true;
  }
}

Upvotes: 1

Infotekka
Infotekka

Reputation: 10443

This is happening because the keypress event fires before the key is sent to the textbox. That is, your code executes, and then a KeyChar 13 is sent to the textbox after.

Try using KeyUp instead.

Upvotes: 1

Lynn Crumbling
Lynn Crumbling

Reputation: 13367

Set multiline property to false?

Upvotes: 1

Related Questions