Home > Software engineering >  second windows requires STA
second windows requires STA

Time:09-04

So I am using AI, to transcribe some text in azure, I am copying the text into background chipboard (That I found here), I am retrieving the text and sending it to a second windows The problem is that Windows gives me this issue

System.InvalidOperationException: 'The calling thread must be STA, because many UI components require this.'

this is the code that is breaking things

    private void SpeechRecognizer_SessionStopped(object? sender, SessionEventArgs e)
{
    var sb = new StringBuilder();

    foreach (var item in Words)
    {
        sb.Append(item);
    }

    BackgroundClipboard.SetText(sb.ToString());

    if (!string.IsNullOrEmpty(BackgroundClipboard.GetText()))
    {
        var spellWindow = new SpellCheckWindow();
        spellWindow.Show();
    }
}

private void SpeechRecognizer_SessionStarted(object? sender, SessionEventArgs e)
{
}

private void SpeechRecognizer_Recognized(object? sender, SpeechRecognitionEventArgs e)
{
    if (e.Result.Reason == ResultReason.RecognizedSpeech)
    {
        foreach (var item in e.Result.Text)
        {
            Words.Add(item);
        }
    }
}

private void SpeechRecognizer_Recognizing(object? sender, SpeechRecognitionEventArgs e)
{
}

}

Error calling the second window

CodePudding user response:

Try create/show the window via the main dispatcher like this

Application.Current.Dispatcher.Invoke(() => {
       var spellWindow = new SpellCheckWindow();
       spellWindow.Show();
});
  • Related