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


Solution 1:

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

Solution 2:

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)



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