私のメインフォームには、テキストボックスの値を数秒ごとに更新するタイマーがあります。コードは次のとおりです。
public partial class Form1 : Form
{
static int column = 2;
static int row = 100;
System.Windows.Forms.TextBox[,] textbox = new System.Windows.Forms.TextBox[column, row];
delegate void StringParameterDelegate(int j, string value);
DisplayTimer displayTimer = new DisplayTimer();
System.Threading.TimerCallback displayCallback;
System.Threading.Timer displayTimerThread;
public Form1()
{
InitializeComponent();
//set the array for name and update time
for (int k = 0; k < column; k++)
{
for (int j = 0; j < row; j++)
{
textbox[k, j] = new System.Windows.Forms.TextBox();
textbox[k, j].Size = new Size(160, 18);
textbox[k, j].Name = "textbox_" + k + "_" + j;
if (j >= 100)
{
textbox[k, j].Location = new System.Drawing.Point((k * 160) + 20, (j * 18) + 30);
}
textbox[k, j].Visible = true;
Controls.Add(textbox[k, j]);
}
}
displayCallback = new System.Threading.TimerCallback(timeDisplay);
displayTimerThread = new System.Threading.Timer(displayCallback, displayTimer, 3000, 3000);
// more code
}
public void timeDisplay(object timerObject)
{
DisplayTimer t = (DisplayTimer)timerObject;
for (int j = 0; j < t.row; j++)
{
string value = t.outputTime[j].ToString("yyyy/MM/dd HH:mm:ss.fff");
writeToTextBox(j, value);
}
}
public void writeToTextBox(int j, string value)
{
if (InvokeRequired)
{
BeginInvoke(new StringParameterDelegate(writeToTextBox), new object[] { j, value });
return;
}
// Must be on the UI thread if we've got this far
textbox[1, j].Text = value;
}
上記のコードは正常に実行され、エラーは発生しません。ただし、私のプログラムには同じメソッドtimeDisplayとwriteToTextBoxを使用する3つのフォームがあり、フォームでコードを3回複製する必要があります。2 つのメソッドをリファクタリングして、新しいクラスに入れようとしました。writeToTextBox メソッドで次のエラーが発生しました。
エラー 1 名前 'InvokeRequired' は現在のコンテキストに存在しません
エラー 2 名前 'BeginInvoke' は現在のコンテキストに存在しません
エラー 3 名前 'textbox' は現在のコンテキストに存在しません
どうすれば効果的にリファクタリングできますか? コードのいくつかの作業スニペットは非常に役立ちます、事前に感謝します
編集:以下は質問の正しいコードです:エラーなしで正常に実行されます。ありがとうチューダー
class DisplayTimer
{
public int numberOfRow = 0;
public int column = 0;
public DateTime[] outputTime;
public System.Windows.Forms.TextBox[,] textbox;
delegate void StringParameterDelegate(TextBox textbox, string value);
public void timeDisplay(object timerObject)
{
DisplayTimer t = (DisplayTimer)timerObject;
for (int j = 0; j < t.numberOfRow; j++)
{
string value = t.outputTime[j].ToString("yyyy/MM/dd HH:mm:ss.fff");
if (value != "0001/01/01 00:00:00.000")
{
writeToTextBox(textbox[column, j], value);
}
}
}
public void writeToTextBox(TextBox textbox, string value)
{
if (textbox.InvokeRequired)
{
textbox.BeginInvoke(new StringParameterDelegate(writeToTextBox), new object[] { textbox, value });
return;
}
// Must be on the UI thread if we've got this far
textbox.Text = value;
}
}