Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackgroundWorker and Clipboard

I'm going crazy with a simple code in which I use a BackgroundWorker to automate the basic operations. Should I add a content to the clipboard.

After executing this code in the method of the BackgroundWorker:

Clipboard.SetText (splitpermutation [i]);

I get an error that explains the thread must be STA, but I do not understand how to do. Here more code: (not all)

private readonly BackgroundWorker worker = new BackgroundWorker();

private void btnAvvia_Click(object sender, RoutedEventArgs e)
{
    count = lstview.Items.Count;
    startY = Convert.ToInt32(txtY.Text);
    startX = Convert.ToInt32(txtX.Text);
    finalY = Convert.ToInt32(txtFinalPositionY.Text);
    finalX = Convert.ToInt32(txtFinalPositionX.Text);
    incremento = Convert.ToInt32(txtIncremento.Text);
    pausa = Convert.ToInt32(txtPausa.Text);

    worker.WorkerSupportsCancellation = true;
    worker.RunWorkerAsync();

    [...]
}

private void WorkFunction(object sender, DoWorkEventArgs e)
{
    [...]

    if (worker.CancellationPending)
    {
        e.Cancel = true;
        break;
    }
    else
    {
        [...]
        Clipboard.SetText(splitpermutation[i]);
        [...]
    }
}
like image 991
user2263764 Avatar asked Apr 09 '13 21:04

user2263764


1 Answers

You could marshal this to the UI thread to make it work:

else
{
    [...]
    this.Dispatcher.BeginInvoke(new Action(() => Clipboard.SetText(splitpermutation[i])));
    [...]
}
like image 175
Reed Copsey Avatar answered Sep 23 '22 17:09

Reed Copsey