如何关闭C#中Application.run()方法创建的表单对象?

时间:2013-11-05 09:24:03

标签: c# winforms

我正在研究C#win form application。我的问题是,当我点击菜单时,我创建了一个显示进度的单独线程(启动进度表单)。当我中止线程时,进度表仍然显示..!但是当我将鼠标指针移到表格上时它会消失 立即..!

以下是我的代码

Thread progressThread = new Thread(() => Application.Run(new frmOperationProgress()));

progressThread.IsBackground = true;
progressThread.Start();
//Some work
progressThread.Abort();

如何在c#

中关闭此进度表单对象

3 个答案:

答案 0 :(得分:1)

问题在于使用Abort - 通常不建议这样做,因为无法保证它会按预期执行(在您的情况下隐藏表单)。

最好在您的帖子中添加适当的取消支持,并直接隐藏初始屏幕。

答案 1 :(得分:1)

请永远不要使用Abort()。这种工作最好通过BackgroundWorker完成;如果你坚持使用线程

尝试:

var form = new frmOperationProgress();
Thread progressThread = new Thread(() => Application.Run(form));
progressThread.IsBackground = true; 
progressThread.Start();
//Some work
form.ExternalClose();

其中ExternalClose是这样的形式的方法:

public void ExternalClose() {
  if (InvokeRequired) {
    Invoke(new MethodInvoker(() => { ExternalClose(); }));
  } else {
    Close();
  }
}

使用BackgroundWorker的解决方案:

在backround worker中,你必须在ProgressChanged事件(在UI线程中运行)中执行UI工作,并在DoWork事件(后台线程)中执行脏工作。

FormMain.cs :(具有单个BackgroundWorker控件的表单,名为“backgroundWorker1”,带有有线事件backgroundWorker1_DoWork,backgroundWorker1_ProgressChanged和WorkerReportsProgress设置为true)

using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApplication1 {
  public partial class FormMain : Form {
    private FormProgress m_Form;
    public FormMain() {
      InitializeComponent();
      backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
      backgroundWorker1.ReportProgress(0, "hello");
      Thread.Sleep(2000);
      backgroundWorker1.ReportProgress(20, "world");
      Thread.Sleep(2000);
      backgroundWorker1.ReportProgress(40, "this");
      Thread.Sleep(2000);
      backgroundWorker1.ReportProgress(60, "is");
      Thread.Sleep(2000);
      backgroundWorker1.ReportProgress(80, "simple");
      backgroundWorker1.ReportProgress(100, "end");
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) {
      if (e.ProgressPercentage == 0 && m_Form == null) {
        m_Form = new FormProgress();
        m_Form.Show();
      }

      if (e.ProgressPercentage == 100 && m_Form != null) {
        m_Form.Close();
        m_Form = null;
        return;
      }

      var message = (string)e.UserState;
      m_Form.UpdateProgress(e.ProgressPercentage, message);
    }
  }
}

FormProgress是一个简单的表单,包含ProgressBar progressBar1和Label label1以及一个额外的方法:

public void UpdateProgress(int percentage, string message) {
  this.progressBar1.Value = percentage;
  this.label1.Text = message;
}

答案 2 :(得分:0)

你可以关闭你的表单,线程(被该表单的消息循环阻止)将自然结束:

var yourForm = new frmOperationProgress();
//Start it
Thread progressThread = new Thread(() => Application.Run(yourForm));
progressThread.IsBackground = true;
progressThread.Start();
//....
//close it
yourForm.Invoke((Action)(() => yourForm.Close()));