Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change focus control when press enter key

Tags:

c#

.net

winforms

I have a windows form, i need when user press Enter set focus to next control. Any idea how to achive this (without using Key Press events)

like image 855
user1659922 Avatar asked Jan 16 '13 04:01

user1659922


2 Answers

You can catch the 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);
}
like image 106
John Koerner Avatar answered Oct 03 '22 03:10

John Koerner


You can use ProcessCmdKey checking if keyData contains the Enter Key then using the SelectNextControl Method to set your 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);
}
like image 23
Mark Hall Avatar answered Oct 03 '22 04:10

Mark Hall