如何通过键盘滚动面板? [英] How to scroll Panel by keyboard?

查看:106
本文介绍了如何通过键盘滚动面板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Inside a form, I have a Panel that contains a single PictureBox and nothing else. One of the requirements is that the user should be able to scroll through the contents of that panel by using only the keyboard. In other words, they would first need to tab into the panel and then use the Up/Down or PageUp/PageDown keys to scroll.

根据Microsoft文档,

According to the Microsoft Docs,

TabStop属性对Panel控件没有影响,因为它是一个 容器对象.

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

在尝试之后,这似乎是真的.当查找PictureBox的TabStop属性时,它类似于

Which, after trying it out appears to be very true. It's similar when looking up a TabStop property for the PictureBox, where it just says

此属性与此类无关.

This property is not relevant for this class.

我尝试在面板上添加VScrollBar并将其TabStop设置为True,但这似乎无济于事.

I tried adding a VScrollBar to the panel and setting its TabStop to True, but that didn't seem to do anything.

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

What is the best way to achieve the desired effect?

推荐答案

您可以从Panel派生并将其设置为Selectable并将其TabStop设置为true.然后,足以覆盖ProcessCmdKey并处理箭头键进行滚动.别忘了也将其AutoScroll设置为true.

You can derive from Panel and make it Selectable and set its TabStop to true. Then It's enough to override ProcessCmdKey and handle arrow keys to scroll. Don't forget to set its AutoScroll to true as well.

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

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

这篇关于如何通过键盘滚动面板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆