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
Maybe I got you wrong, but what I would do is:
- Set the "AcceptButton" of the form to the Button you want to respond on "Enter"
- Set the "AcceptsReturn" of the textbox with multiline to true
et voila
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.
(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);
}
}
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