C# How to click a button by hitting Enter whilst textbox has focus

cwinforms

I'm working with a WinForm app in C#, after I type something in a textbox I want to hit the Enter key but the textbox still has focus (flashing cursor is still in textbox), how can I achieve this?

Best Answer

The simple option is just to set the forms's AcceptButton to the button you want pressed (usually "OK" etc):

    TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });

If this isn't an option, you can look at the KeyDown event etc, but that is more work...

    TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    tb.KeyDown += (sender,args) => {
        if (args.KeyCode == Keys.Return)
        {
            btn.PerformClick();
        }
    };
    Application.Run(new Form { Controls = { tb, btn } });