ボタン、ラベル、進行状況バーを含むフォームがあるので、ボタンをクリックするとクラス b のインスタンスが作成され、プロセスが実行されます。プロセスが完了すると、EventHandler が呼び出され、メイン フォームのラベルに「完了」が表示されます。
これを行うために、デリゲート (SetStatus) のイベント (SetStatusEvent) を作成しました。そして、このイベントを EventHandler (usbforProcessExited) の外で呼び出すと問題ないように見えますが、usbforProcessExited から呼び出すとエラーが発生します -
object reference not set to an instance of an object
メインフォーム
public partial class main : Form
{
b rsSet = new b();
public main()
{
InitializeComponent();
rsSet.SetStatusEvent += new RemoteS.SetStatus(updateStatus);
}
private void button1_Click(object sender, EventArgs e)
{
rsSet.FormatUSB();
}
private delegate void UpdateStatus(int i, string str, Color clr);
private void SetStatus(int i, string str, Color clr)
{
this.progressBar1.Value = i;
this.lbl_status.ForeColor = clr;
this.lbl_status.Text = str;
}
private void updateStatus(int i, String msg, Color color)
{
object[] p = GetInokerPara(i, msg, color);
BeginInvoke(new UpdateStatus(SetStatus), p);
}
private object[] GetInokerPara(int progress, string msg, Color color)
{
object[] para = new object[3];
para[0] = progress;
para[1] = msg;
para[2] = color;
return para;
}
}
クラスb
class b
{
public delegate void SetStatus(int i, string msg, Color color);
public event SetStatus SetStatusEvent;
System.Diagnostics.Process usbfor = new System.Diagnostics.Process();
public void FormatUSB()
{
usbfor.StartInfo.FileName = @"usbformat.bat";
usbfor.EnableRaisingEvents = true;
usbfor.Exited += new EventHandler(usbforProcessExited);
usbfor.Start();
}
public void usbforProcessExited(object sender, EventArgs f)
{
SetStatusEvent(100, "DONE", Color.Green); //ERROR HERE! (object reference not set to an instance of an object
}
}
問題はどこだ?