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

后端 未结 4 1619
情深已故
情深已故 2020-11-30 13:36

I need to disable changing focus with arrows on form. Is there an easy way how to do it?

Thank you

相关标签:
4条回答
  • 2020-11-30 14:16

    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.

    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;
        }
    }
    
    0 讨论(0)
  • 2020-11-30 14:23

    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;
        }
    }
    
    0 讨论(0)
  • 2020-11-30 14:31

    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;
            }
        }
    
    0 讨论(0)
  • 2020-11-30 14:36

    You should set KeyPreview to true on the form. Handle the KeyDown/KeyUp/KeyPress event and set the e.Handled in the eventhandler to true for the keys you want to be ignored.

    0 讨论(0)
提交回复
热议问题