Detect keypressing in a textbox and converting user text to a string

时间:2015-09-01 21:56:50

标签: c# windows-forms-designer

I want to write something in a TextBox, then I want to press Enter and convert the input into a string.

How do you do this in WinForms?

2 个答案:

答案 0 :(得分:1)

For starters, input into a TextBox is already a string and is stored in the Text property. So that part is easy.

Triggering off of the "Enter" key is another story however. The easiest way is with the PreviewKeyDown event. Assign something like the following handler to your text box's PreviewKeyDown event (either in code-behind or through the designer):

void HandleKeyPress(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        string input = (sender as TextBox)?.Text;
        //Your logic
        e.IsInputKey = true; //Don't do standard "Enter" things
    }
}

The reason you use PreviewKeyDown is that the later events (KeyDown, KeyPress, KeyUp) won't trigger on "Enter" because its not a "InputKey". The linked documentation explains is in fuller detail.

Notes:

  • If you want the standard handling of "Enter" to continue, then don't set IsInputKey to true.

  • The first line of the if statement says "Cast the control that raised this event to TextBox and get it's Text property." You could instead use the TextBox's name, or a number of other things.

  • The ?. is in case the cast fails due to the control not actually being a TextBox (input will be null in that case). This is only valid syntax in C# 6.

答案 1 :(得分:0)

The text in the textbox would already be a string. You can grab the text value of the textbox by simply grabbing the .Text property.

See https://msdn.microsoft.com/en-us/library/a19tt6sk(v=vs.110).aspx for more info.