如何通过键盘滚动面板?

How to scroll Panel by keyboard?

在一个表单中,我有一个 Panel,其中包含一个 PictureBox,仅此而已。其中一项要求是用户应该能够仅使用键盘滚动浏览该面板的内容。换句话说,他们首先需要使用 Tab 键进入面板,然后使用 Up/Down 或 PageUp/PageDown 键进行滚动。

根据微软文档,

The TabStop property has no effect on the Panel control as it is a container object.

经过尝试,似乎是真的。查找 PictureBox 的 TabStop 属性 时类似,只是说

This property is not relevant for this class.

我尝试将 VScrollBar 添加到面板并将其 TabStop 设置为 True,但这似乎没有任何作用。

达到预期效果的最佳方法是什么?

您可以从 Panel 派生并使其成为 Selectable 并将其 TabStop 设置为 true。然后它足以覆盖 ProcessCmdKey 并处理箭头键来滚动。不要忘记将其 AutoScroll 也设置为 true。

可选面板 - 可通过键盘滚动

using System.Drawing;
using System.Windows.Forms;
class SelectablePanel : Panel
{
    const int ScrollSmallChange = 10;
    public SelectablePanel()
    {
        SetStyle(ControlStyles.Selectable, true);
        SetStyle(ControlStyles.UserMouse, true);
        TabStop = true;
    }
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (!Focused)
            return base.ProcessCmdKey(ref msg, keyData);

        var p = AutoScrollPosition;
        switch (keyData)
        {
            case Keys.Left:
                AutoScrollPosition = new Point(-ScrollSmallChange - p.X, -p.Y);
                return true;
            case Keys.Right:
                AutoScrollPosition = new Point(ScrollSmallChange - p.X, -p.Y);
                return true;
            case Keys.Up:
                AutoScrollPosition = new Point(-p.X, -ScrollSmallChange - p.Y);
                return true;
            case Keys.Down:
                AutoScrollPosition = new Point(-p.X, ScrollSmallChange - p.Y);
                return true;
            default:
                return base.ProcessCmdKey(ref msg, keyData);
        }
    }
}