使用箭头键滚动ScrollableControl

时间:2013-01-06 10:36:40

标签: c# winforms scroll scrollbar

我在我的C#项目中使用ScrollableControl,我想知道如何将箭头键映射到垂直/水平滚动

编辑:我的图片框得到焦点,我设法映射键滚动。这里的问题是,当我按箭头键时,它会滚动一次,然后失去焦点,将其提供给Scrollviewer旁边的按钮。我希望滚动查看器不要失去焦点

这是我的代码,第二段在这里很有意思。

private void drawMap(IGame game)
{
    System.Windows.Forms.PictureBox pictureBox = new System.Windows.Forms.PictureBox();
    pictureBox.Width = (int)Math.Sqrt((double)game.Map.grid.Count) * 50; pictureBox.Height = (int)Math.Sqrt((double)game.Map.grid.Count) * 50;
    pictureBox.Paint += new System.Windows.Forms.PaintEventHandler(game.Map.afficher);
    pictureBox.MouseEnter += pictureBoxFocus;
    pictureBox.Click += pictureBoxFocus;
    pictureBox.Click += mapClicked;

    System.Windows.Forms.ScrollableControl sc = new System.Windows.Forms.ScrollableControl();
    sc.Controls.Add(pictureBox);
    sc.AutoScroll = true;
    windowsFormsHost1.Child = sc;
}

提前谢谢你:)

PLUS:我的滚动算法有点肮脏,不能很好地工作,所以我想知道是否有一个“简单的方法”来做它。

private void sc_PreviewKeyDown(object sender, System.Windows.Forms.PreviewKeyDownEventArgs e)
{
    System.Windows.Forms.ScrollableControl sc = (System.Windows.Forms.ScrollableControl)sender;
    switch (e.KeyValue)
    {
        case (int)System.Windows.Forms.Keys.Down:
            sc.VerticalScroll.Value += 50;
            break;
        case (int)System.Windows.Forms.Keys.Up:
            if(sc.VerticalScroll.Value - 50 < 0)
                sc.VerticalScroll.Value = 0;
            else sc.VerticalScroll.Value -= 50;
            break;
        case (int)System.Windows.Forms.Keys.Right:
            sc.HorizontalScroll.Value += 50;
            break;
        case (int)System.Windows.Forms.Keys.Left:
            if (sc.HorizontalScroll.Value - 50 < 0)
                sc.HorizontalScroll.Value = 0;
            else sc.HorizontalScroll.Value -= 50;
            break;
    }
    windowsFormsHost1.Child.Focus();
}

0 个答案:

没有答案