I can't seem to have this part of my code to work. The objective for this piece of code is to add a numbered list every time The user presses, "ENTER". Here is and example of what I mean.
0)10100[User presses the ENTER key]
1)(cursor is here)
Here is the code I have. meowbox
is a multiline text box.
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
meowbox.Text += i + ")";
++i;
}
base.OnKeyDown(e);
}
It looks like you may not be putting your code in the correct method. One easy way to do it is to go to your form designer, select the textbox, go to the Properties window, click the lightning-bolt icon (for methods), and then double-click the KeyDown
method. This will create an event handler and hook it up to the text box.
Another problem you may have (once you get it hooked up correctly) is that the textbox continues to process the key press even though you are handling it yourself. To get around this, you can set SuppressKeyPress
to true
.
For example:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox1.Text += Environment.NewLine + i++ + ") ";
textBox1.SelectionStart = textBox1.Text.Length;
e.SuppressKeyPress = true;
}
}