简体   繁体   English

如何在 C# 中使用箭头禁用 WinForm 上的导航?

[英]How to disable navigation on WinForm with arrows in C#?

I need to disable changing focus with arrows on form.我需要禁用使用表单上的箭头更改焦点。 Is there an easy way how to do it?有没有简单的方法来做到这一点?

Thank you谢谢

Something along the lines of:类似的东西:

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (Control control in this.Controls)
        {
            control.PreviewKeyDown += new PreviewKeyDownEventHandler(control_PreviewKeyDown);
        }
    }

    void control_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
        {
            e.IsInputKey = true;
        }
    }

I've ended up with the code below which set the feature to EVERY control on form:我已经结束了下面的代码,该代码将功能设置为表单上的每个控件:

(The code is based on the one from andynormancx) (该代码基于来自andynormancx 的代码)



private void Form1_Load(object sender, EventArgs e)
{
    SetFeatureToAllControls(this.Controls);    
}

private void SetFeatureToAllControls(Control.ControlCollection cc)
{
    if (cc != null)
    {
        foreach (Control control in cc)
        {
            control.PreviewKeyDown += new PreviewKeyDownEventHandler(control_PreviewKeyDown);
            SetFeatureToAllControls(control.Controls);
        }
    }
}

void control_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
    {
        e.IsInputKey = true;
    }
}

You should set KeyPreview to true on the form.您应该在表单上将KeyPreview设置为 true。 Handle the KeyDown/KeyUp/KeyPress event and set the e.Handled in the eventhandler to true for the keys you want to be ignored.处理KeyDown/KeyUp/KeyPress事件并将事件处理程序中的e.Handled设置为 true 以用于要忽略的键。

I tried this aproach, where the form handles the preview event once.我试过这种方法,表单处理一次预览事件。 It generates less code than the other options.它生成的代码比其他选项少。

Just add this method to the PreviewKeyDown event of your form, and set the KeyPreview property to true .只需将此方法添加到表单的PreviewKeyDown事件中,并将KeyPreview属性设置为true

private void form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Up:
        case Keys.Down:
        case Keys.Left:
        case Keys.Right:
            e.IsInputKey = true;
            break;
        default:
            break;
    }
}

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

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