0x49D1
0x49D1

Reputation: 8704

Default button hit in windows forms (trying to find the best solution)

The question is: How to make default button be focused on form focus and response on "Enter" hit, but not focused when the caret is in textbox with multiline property set to true for example?..I know that i can do some exceptions in code, but maybe there is some "best practices" i dont know for now :( thank you

Upvotes: 9

Views: 15259

Answers (6)

RAVI VAGHELA
RAVI VAGHELA

Reputation: 897

Do as following:

private void Login_Load(object sender, EventArgs e)
{
    this.AcceptButton = btnLogin;
}

Upvotes: 0

nijas
nijas

Reputation: 1899

on Form_Load, set

this.AcceptButton = buttonName;

Upvotes: 0

Dean
Dean

Reputation: 65

or you can do it in de focus event of your textbox as in

_targetForm.AcceptButton = _targetForm.btnAccept;

and then ubind it in the other textbox with multilines

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062540

(edit - the answer here is very good for TextBox; this pattern might be useful for other controls that lack the AcceptsReturn or equivalent)

You can use the GotFocus and LostFocus events to change the AcceptButton fairly easily, for example:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    TextBox multi, single;
    Button btn;
    using(Form form = new Form {
            Controls = {
                (multi= new TextBox { Multiline = true, Dock = DockStyle.Fill}),
                (btn = new Button { Text = "OK", Dock = DockStyle.Bottom,
                    DialogResult = DialogResult.OK}),
                (single = new TextBox { Multiline = false, Dock = DockStyle.Top}),
            }, AcceptButton = btn                
        })
    {
        multi.GotFocus += delegate { form.AcceptButton = null; };
        multi.LostFocus += delegate { form.AcceptButton = btn; };
        btn.Click += delegate { form.Close(); };
        Application.Run(form);
    }
}

Upvotes: 5

Rune Grimstad
Rune Grimstad

Reputation: 36300

A Windows Form has two properties: AcceptButton and CancelButton. You can set these to refer button controls on your form. The AcceptButton tells which button should be clicked when the user presses the enter key, while the Cancel button tells which button should be clicked when the user presses the escape key.

Often you will set the DialogResult of the AcceptButton to DialogResult.OK or DialogResult.Yes and DialogResult.Cancel or DialogResult.No for the CancelButton. This ensures that you can easily check which button was clicked if you dispay the form modally.

Upvotes: 4

Xn0vv3r
Xn0vv3r

Reputation: 18184

Maybe I got you wrong, but what I would do is:

  1. Set the "AcceptButton" of the form to the Button you want to respond on "Enter"
  2. Set the "AcceptsReturn" of the textbox with multiline to true

et voila

Upvotes: 15

Related Questions