【トラブル】【C#】PictureBoxの親のPanelを非活性にしたところSystem.ArgumentExceptionが発生する

■ はじめに

 PictureBoxの親のPanelを非活性にしたところ、
System.ArgumentExceptionが発生したので調査。

■ 例外内容

型 'System.ArgumentException' のハンドルされていない例外が System.Drawing.dll で発生しました
使用されたパラメーターが有効ではありません。

System.ArgumentException
  HResult=0x80070057
  Message=使用されたパラメーターが有効ではありません。
  Source=System.Drawing
  スタック トレース:
   at System.Drawing.Image.get_Width()
   at System.Drawing.Image.get_Size()
   at System.Windows.Forms.PictureBox.ImageRectangleFromSizeMode(PictureBoxSizeMode mode)
   at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
   at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
   at System.Windows.Forms.Control.WmPaint(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

■ 現象が再現できるサンプル

以下のサンプルで
button1(画像表示)  => button2 => button3 って押していくと
上記の例外が発生する
(デバッグビルド、リリースビルドどちらでも発生)

Form1.cs

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

namespace SampleForm
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      this.pictureBox1.Image = new Bitmap(@"C:\temp\20161215052204.gif");
    }

    private void button2_Click(object sender, EventArgs e)
    {
      if (this.pictureBox1.Image != null)
      {
        this.pictureBox1.Image.Dispose();
      }
    }

    private void button3_Click(object sender, EventArgs e)
    {
      // button1(画像表示)  => button2 => button3 って押していくと...
      // ここで例外が発生する ★注目★
      this.panel1.Enabled = false;
    }

    private void button4_Click(object sender, EventArgs e)
    {
      // button1(画像表示) => button4(画像が切れる) => button3 って押した場合...
      // 例外は発生しない ★ここにも注目★
      if (this.pictureBox1.Image != null)
      {
        this.pictureBox1.Image.Dispose();
        this.pictureBox1.Image = null;
      }
    }
  }
}

■ 原因

pictureBox.Image.Dispose()していたため

■ 解決案

pictureBox.Image.Dispose()した後に、明示的に null を格納する

詳細は、上記のサンプルの「button4_Click」の実装を参照のこと


関連記事

Windows Form

Windows Form ~ 目次 ~
https://blogs.yahoo.co.jp/dk521123/8054245.html