Change focus control when you press the enter key

I have a window shape, I need it when the user presses Enter to adjust focus to the next control. Any idea how to achieve this (without using keypress events)

+6
source share
3 answers

You can catch KeyPreview of your form. Set KeyPreview to true in the constructor, and then you can use this:

protected override bool ProcessKeyPreview(ref Message m) { if (m.Msg == 0x0100 && (int)m.WParam == 13) { this.ProcessTabKey(true); } return base.ProcessKeyPreview(ref m); } 
+6
source

You can use the ProcessCmdKey check if keyData contains an Enter key, and then SelectNextControl A way to adjust the focus.

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData.HasFlag(Keys.Enter)) { SelectNextControl(ActiveControl,true,true,true,true); return true; //Stops the beeping } return base.ProcessCmdKey(ref msg, keyData); } 
+1
source

If you do not want to use keystroke events, you will have to override ProcessCmdKey

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.Return) { MessageBox.Show("You pressed the Enter key"); } return base.ProcessCmdKey(ref msg, keyData); } 
0
source

All Articles