简体   繁体   English

按enter键改变焦点控制

[英]Change focus control when press enter key

I have a windows form, i need when user press Enter set focus to next control. 我有一个Windows窗体,我需要当用户按Enter键设置焦点到下一个控件。 Any idea how to achive this (without using Key Press events) 知道如何实现这一点(不使用按键事件)

You can catch the KeyPreview of your form. 您可以捕获表单的KeyPreview。 Set KeyPreview to true in the constructor and then you can use this: 在构造函数中将KeyPreview设置为true,然后您可以使用:

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. 您可以使用ProcessCmdKey检查keyData是否包含Enter键,然后使用SelectNextControl方法设置焦点。

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 如果您不想使用按键事件,则必须覆盖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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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