在 Windows 表单中显示 textBox.Text 并通过 "idx" 迭代 for 循环

Display textBox.Text in Windows Form with "idx" iterating through for loop

这是我的第一个 C# 项目。我有两个 .cs 文件,一个包含所有与 GUI 相关的内容 (Form1.cs),另一个包含我的处理 (GMF.cs)。当用户单击 GUI 上的 "Start"(Button)时,控制权将传递给 Form1.cs,后者会在内部调用 GMF.cs 文件中的 GMFMat()。

在Form1.cs中,我有:

private void button1_Click(object sender, EventArgs e) // Start Processing button clicked.
{
    GMF n = new GMF();
    func_out = n.GMFMat(inputs_GUI, this.progressBar1, this.textBox_imageNumber);
}

private void timer1_Tick(object sender, EventArgs e) // Increment Progress Bar
{
    progressBar1.Increment(1);
}

private void textBox_imageNumber_TextChanged(object sender, EventArgs e)
{
    this.Text = textBox_imageNumber.Text;
    Console.Write("Text = " + textBox_imageNumber.Text);
}

在GMF.cs中,我有:

class GMF
{
public Tuple<string, int> GMFMat(in_params input_from_GUI, System.Windows.Forms.ProgressBar bar, System.Windows.Forms.TextBox textBox_ImgNumber) 
{
    double nth_file = 0;
    double num_files = 100
    foreach (string dir in dirs) // For our example, say 100 ierations
    {
        nth_file = nth_file + 1;
        textBox_ImgNumber.Text = nth_file.ToString();
        // Progress bar updates in each iteration, and I can see it as it progresses on the windows Form during execution. 
        bar_value_percent = nth_file / num_files * 100;
        bar.Value = int.Parse(Math.Truncate(bar_value_percent).ToString());
    }
}
}

Form1.cs[Design] 有一个文本框(我从工具箱中简单地拖放了它)。我重命名 (Name) = textBox_imageNumber

当我 运行 上面的代码时,我注意到以下内容:

  1. 在控制台 window 上,输出符合预期:Text = 1, Text = 2, ... Text = 100 随着程序的进行。 - 这表明 textBox_ImgNumber.Text 中的变量值正在 GMF.cs 的 for 循环内更新,并达到 Form1.cs.

  2. 但是,在窗体上,文本框中的值在程序 运行s(在 for 循环内)时为空。一出来func_out = n.GMFMat(inputs_GUI, this.progressBar1, this.textBox_imageNumber);,textBox的值就显示为100.

我希望在 for 循环迭代时更新表单上文本框的值(正如我在控制台 window 上看到的那样)。我该怎么做?

我在 Visual Studio 2010 上使用 Visual Studio、C#、.NET Framework 4 客户端配置文件

我知道我的表单在处理等方面运行良好,因为其他功能在两个 .cs 文件之间沟通良好。

比如我还有一个进度条,在程序执行的时候可以看到进度条。

我找到了解决方案。

我必须包含以下行:Application.DoEvents();

所以 Form1.cs:

private void textBox_imageNumber_TextChanged(object sender, EventArgs e)
{
     this.Text = textBox_imageNumber.Text;
     Console.Write("Text = " + textBox_imageNumber.Text);
     Application.DoEvents();
}