简体   繁体   中英

Change focus control when press enter key

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)

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);
}

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);
}

If you dont want to use key press 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM