PictureBox の画像を切り替える

PictureBox と Button を貼り付けて、ボタン操作で二枚の画像を切り替えます。

前田稔(Maeda Minoru)の超初心者のプログラム入門

プログラムの説明

  1. PictureBox を貼り付けて画像を描画する簡単な方法は PictureBox に画像を描画 を参照して下さい。
    今回は ToolBox を使わずに、直接プログラムで [PictureBox] と [Button] を貼り付けます。
    従って、空のプロジェクトを作成して、下記のプログラムをプロジェクトに組み込んで下さい。
  2. img1 と img2 が切り替える二枚の画像ファイルです。
    テストするときは、PictureBox のサイズに合わせて適当な画像を調達して下さい。
    画像ファイルの名前をフルパスで指定します。
    「@」を使う方法と「\\」を使う方法の二通りで画像ファイルを定義してみました。
    最初は MyForm() で pictureBox1.Image = img1; に設定しています。
    flag は ON(1), OFF(0) の状態を記憶する領域です。
        Image   img1 = Image.FromFile(@"C:\Data\Test\Kishi.gif");
        Image   img2 = Image.FromFile("C:\\Data\\Test\\ayu.gif");
        int flag = 1;
        
  3. ボタンがクリックされたときの EventHandler です。
    flag ^= 1; でボタンがクリックされる毎に、0と1を交互に切り替えます。
    pictureBox1.Image が PictureBox に表示されるイメージの領域です。
    flag==1 のときは img1 の画像を、flag==0 のときは img2 の画像を設定します。
        private void Button1_Click(object sender, EventArgs e)
        {
            flag ^= 1;
            if (flag==1)    pictureBox1.Image = img1;
            else            pictureBox1.Image = img2;
            //else            pictureBox1.Image = null;
        }
        
    Image に null を設定すると PictureBox の画像が描画されなくなるので試して下さい。
  4. ソースコードです。
    /************************************************/
    /*★ PictureBox の画像を切り替える    前田 稔 ★*/
    /************************************************/
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    public class MyForm : Form
    {
        private Button button1;
        private PictureBox pictureBox1;
        Image   img1 = Image.FromFile(@"C:\Data\Test\Kishi.gif");
        Image   img2 = Image.FromFile("C:\\Data\\Test\\ayu.gif");
        int flag = 1;
    
        public MyForm()
        {
            // button1
            button1 = new Button();
            button1.Parent = this;
            button1.Location = new Point(90, 221);
            button1.Text = "押す";
            button1.BackColor = SystemColors.Control;
            button1.Click += new System.EventHandler(Button1_Click);
    
            // pictureBox1
            pictureBox1 = new System.Windows.Forms.PictureBox();
            pictureBox1.Location = new Point(12, 12);
            pictureBox1.Size = new Size(258, 198);
    
            // MyForm
            Controls.Add(button1);
            Controls.Add(pictureBox1);
    
            pictureBox1.Image = img1;
        }
    
        private void Button1_Click(object sender, EventArgs e)
        {
            flag ^= 1;
            if (flag==1)    pictureBox1.Image = img1;
            else            pictureBox1.Image = img2;
            //else            pictureBox1.Image = null;
        }
    }
    
    class form01
    {
        public static void Main()
        {
            MyForm mf = new MyForm();
            Application.Run(mf);
        }
    }
    

超初心者のプログラム入門(C# Frame Work)