Overriding Key Strokes

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I need to override the Enter key for the entire form. In my Windows form,
when a user presses Enter, I want it to behave just like a Tab, except when
the focus is on a button. Here are the 2 methods I've tried:

public EstDefaults()
{
InitializeComponent();

KeyPress += new KeyPressEventHandler(EstDefaults_KeyPress);
}


private void EstDefaults_KeyPress(object sender, KeyPressEventArgs e)
{
if (!exit.Focused || !cancel.Focused || !Delete.Focused)
{
e.KeyChar = (char)9;
}
}


AND


public EstDefaults()
{
InitializeComponent();

KeyDown += new KeyEventHandler(EstDefaults_KeyDown);
}

private void EstDefaults_KeyDown(object sender, KeyEventArgs e)
{
if (!exit.Focused || !cancel.Focused || !Delete.Focused )
{
e.KeyCode = Keys.Tab;
}
}


The KeyPress does nothing, and the KeyDown won't compile because e.KeyCode
is read-only. KeyPreview is set to True at the form level.

What am I doing wrong? Thanks!
 
Use keypress. If the key is "enter", set e.handled to "true". That
will make the control ignore the "enter" event. Then you can use the
GetNextControl().Focus or SelectNextControl methods (not sure which) to
handle activating the next control.
 
Thanks, I'll try it.

If it ignores the Enter key, will it still go through the validation process?
 
Back
Top