VSTO - 在异步BackgroundWorker运行时禁用Excel

时间:2018-05-09 16:04:36

标签: c# excel vsto

我有一个VSTO加载项我正在为Excel开发。表单允许用户从数据库中查询表,然后适当地填充。 Bellow是我的BackGround Worker的代码,因为你可以看到它运行Async并完美地报告了进度。

我的问题是,当进程正在运行时,用户可以操作并单击Excel。我知道这是异步函数的重点,但在这种情况下会导致BackgroundWorker中断。有没有办法完全禁用点击或活动表?

private void button1_Click(object sender, EventArgs e)
{
    //run
    //this.backgroundWorker3.RunWorkerAsync();

    System.Threading.SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());

    BackgroundWorker bw = new BackgroundWorker();
    bw.WorkerReportsProgress = true;
    bw.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker3_ProgressChanged);
    bw.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker3_DoWork);

    bw.RunWorkerAsync();


}

private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
{

    BackgroundWorker worker = (BackgroundWorker)sender;
    worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker3_WorkerCOmpleted);
    if (!_isExtended)
    {
         oneline ol = new oneline();
         ol.buildOneline(this._wheres,worker );
    }
    else
    {
       ExtendedOneline ole = new ExtendedOneline();
        ole.buildExtendedOneline(this._wheres,worker);
    }
    //worker.ReportProgress();
     e.Result = "COMPLETE!";


 }

2 个答案:

答案 0 :(得分:1)

请注意,VSTO中的多线程通常不是一个好主意。但是我使用进度对话框(I started with this one)取得了成功。你仍然只运行一个与API交互的线程,所以我可以告诉你。

你这样称呼它:

ProgressDialogResult result = ProgressDialog.Execute(parent, name, () =>
{
    // do whatever
}, new ProgressDialogSettings(true, true, false));

您也可以使用WdProtectionType暂时禁用编辑(这适用于Word但我想Excel有类似的东西,可能是XlProtectionType?)但我不推荐它。

答案 1 :(得分:0)

我相信你可以简单地使用:

 Globals.ThisAddIn.Application.Cursor = Excel.XlMousePointer.xlWait

// ... your BackgroundWorker Running here

 Globals.ThisAddIn.Application.Cursor = Excel.XlMousePointer.xlDefault;

或者可能与:Globals.ThisAddIn.Application.ScreenUpdating