c#使用VSTO插件的Winform控件保持Excel响应

问题描述 投票:1回答:2

我是VSTO Excel Addin和Winforms的新手。我创建了一个插件,它启动一个winform页面,其中包含几个复选框,一个按钮和一个标签以显示状态。

enter image description here

一旦winform启动,我的excel就没有响应。即使打开winform(并点击“完成”按钮),我也想让excel响应。 Button将运行一个长时间运行的进程。我怎样才能做到这一点?有什么指针吗?

这就是我的Ribbon类:

public partial class Ribbon1
    {
        private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
        {

        }

        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            Form1 fs = new Form1();
            fs.ShowDialog();
        }

    }

表格类别:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "Processing please wait";
            await Task.Run(() => { longRunningProcess(); });
            label1.Text = "File 1 Processed";
        }
         public void longRunningProcess()
        {
            Thread.Sleep(5000);
        }
    }

更新:使用.show工作,但我无法访问label1.Text并获取错误:

System.InvalidOperationException: 'Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.'

enter image description here

c# excel winforms vsto excel-addins
2个回答
1
投票

使用Show打开表单并使用Invoke编组回UI线程。


1
投票

@Sievajet帮助解决了这个问题。发布代码,以防有人需要它。

private async void button1_Click(object sender, EventArgs e)
        {
            label1.Text = "Processing please wait";
            await Task.Run(() => { longRunningProcess(); });
            label1.Invoke((MethodInvoker)delegate {
                label1.Text = "File 1 Processed";
            });
        }
© www.soinside.com 2019 - 2024. All rights reserved.