Mozes i ovako:
Code:
public class Form1: Form
{
...
public Form1()
{
...
FormHelpers.SetupFormKeyboardEvents(this, true, true); // samo dodas ovu liniju u formu
}
}
Code:
public class FormHelpers
{
/// <summary>
/// Adds KeyDown event listener which closes form on Escape key,
/// and KeyPress event which selects next form control on Enter
/// </summary>
public static void SetupFormKeyboardEvents(Form form, bool closeOnEscape, bool selectNextControlOnEnter)
{
form.KeyPreview = true;
if(closeOnEscape) {
form.KeyDown += new KeyEventHandler(form_KeyDown_CloseOnEscape);
form.CancelButton = null;
}
if(selectNextControlOnEnter) {
form.KeyDown += new KeyEventHandler(form_KeyDown_SelectNextControlOnEnter);
form.AcceptButton = null;
}
}
public static void RemoveFormKeyboardEvents(Form form)
{
form.KeyDown -= form_KeyDown_CloseOnEscape;
form.KeyDown -= form_KeyDown_SelectNextControlOnEnter;
}
#region SetupFormKeyboardEvents handlers
private static void form_KeyDown_CloseOnEscape(object sender, KeyEventArgs e)
{
try { if(e.KeyCode == Keys.Escape) ((Form)sender).Close(); } catch { };
}
private static void form_KeyDown_SelectNextControlOnEnter(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter) FormHelpers.SelectFormNextControl((Form)sender, true);
}
#endregion
/// <summary>
/// Moves focus to next control (and selects all text if it is a text box)
/// </summary>
/// <param name="form">Form that contains controls to inspect and move focus.</param>
/// <param name="tabStopOnly">If true, inspect only controls with TabStop set.</param>
public static void SelectFormNextControl(Form form, bool tabStopOnly)
{
Control control = GetContainerActiveControl(form);
if(form != null && control != null) {
try {
bool isTextBoxBaseSubclass = control.GetType().IsSubclassOf(typeof(System.Windows.Forms.TextBoxBase));
if(isTextBoxBaseSubclass && ((TextBoxBase)control).Multiline) return;
form.SelectNextControl(control, true, tabStopOnly, true, true);
if(isTextBoxBaseSubclass) ((TextBoxBase)control).SelectAll();
} catch { }
}
}
/// <summary>
/// Returns container currently active control (not container control)
/// </summary>
/// <returns>Returns null if it fails</returns>
public static Control GetContainerActiveControl(ContainerControl containerControl)
{
if(containerControl == null) return null;
Control control = containerControl.ActiveControl;
while(control != null && control.GetType().IsSubclassOf(typeof(ContainerControl))) control = GetContainerActiveControl((ContainerControl)control);
return control;
}
}
Sa ovom pomocnom metodom mozes selektovati sledecu kontrolu pomocu entera, kada se selektuje textbox selektuje se ceo text u kontroli, ako je textbox multiline nece se obradjivati enter, mozes da stavis da se forma zatvori na escape.