Panel not getting focus

后端 未结 6 2231
小鲜肉
小鲜肉 2020-11-22 14:42

I am continuing to program some kind of keyboard navigation in my simple graphic program (using C#). And I ran into trouble once again.

6条回答
  •  日久生厌
    2020-11-22 15:16

    The Panel class was designed as container, it avoids taking the focus so a child control will always get it. You'll need some surgery to fix that. I threw in the code to get cursor key strokes in the KeyDown event as well:

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    class SelectablePanel : Panel {
        public SelectablePanel() {
            this.SetStyle(ControlStyles.Selectable, true);
            this.TabStop = true;
        }
        protected override void OnMouseDown(MouseEventArgs e) {
            this.Focus();
            base.OnMouseDown(e);
        }
        protected override bool IsInputKey(Keys keyData) {
            if (keyData == Keys.Up || keyData == Keys.Down) return true;
            if (keyData == Keys.Left || keyData == Keys.Right) return true;
            return base.IsInputKey(keyData);
        }
        protected override void OnEnter(EventArgs e) {
            this.Invalidate();
            base.OnEnter(e);
        }
        protected override void OnLeave(EventArgs e) {
            this.Invalidate();
            base.OnLeave(e);
        }
        protected override void OnPaint(PaintEventArgs pe) {
            base.OnPaint(pe);
            if (this.Focused) {
                var rc = this.ClientRectangle;
                rc.Inflate(-2, -2);
                ControlPaint.DrawFocusRectangle(pe.Graphics, rc);
            }
        }
    }
    

提交回复
热议问题