header
CodePanic! > C#.NET Tips > 今ここ

■スクロールバーの使い方

FormやTextBoxなど、コントロールにスクロールバーを表示する方法もありますが
スクロールバー単体のコントロールも用意されています。

例では
FormにPictureBoxを貼り付けて、起動時に適当な画像を読み込み
(PictureBoxのサイズよりも大きな画像ファイルがいいです)
それをスクロールバーでスクロール表示させています。
scrollbar.jpg(34468 byte)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        // 適当な画像を指定(大きいのがいいです)
        Bitmap _bmp = new Bitmap(@"c:\temp\sample.jpg");

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // PictureBoxの再描画が必要な時に呼ばれるハンドラ
            this.pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint);

            // 縦スクロールバーの初期位置、最小値、最大値を設定
            this.vScrollBar1.Value = 0;
            this.vScrollBar1.Minimum = 0;
            this.vScrollBar1.Maximum = _bmp.Height - pictureBox1.Height;

            // 横スクロールバーの初期位置、最小値、最大値を設定
            this.hScrollBar1.Value = 0;
            this.hScrollBar1.Minimum = 0;
            this.hScrollBar1.Maximum = _bmp.Width - pictureBox1.Width;

            // スクロールバーがスクロールされた際のイベントハンドラ
            this.vScrollBar1.Scroll += new ScrollEventHandler(ScrollBar_Scroll);
            this.hScrollBar1.Scroll += new ScrollEventHandler(ScrollBar_Scroll);
        }

        void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            // スクロールバー位置より元画像を切り抜いて表示
            RectangleF rectSrc = new RectangleF(
                this.hScrollBar1.Value,
                this.vScrollBar1.Value,
                this.pictureBox1.Width,
                this.pictureBox1.Height);
            e.Graphics.DrawImage(_bmp, 0, 0, rectSrc, GraphicsUnit.Pixel);
        }

        void ScrollBar_Scroll(object sender, ScrollEventArgs e)
        {
            // スクロールされたので再描画
            this.pictureBox1.Refresh();
        }
    }
}





Copyright © 2008.07 - shougo suzaki