调用线程必须为 STA,因为许多 UI 组件都需要

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenqiai0/article/details/8439782
class Mainclass
    {
        [STAThread]
        static void Main()
        {
            Application app = new Application();
            MainWindow win = new MainWindow();

            app.Startup += new StartupEventHandler(app_Startup);
            app.Run();
        }

        static void app_Startup(object sender,StartupEventArgs e)
        {
            MessageBox.Show("fdf");
        }
    }

需要在 Main() 方法前添加 [STAThread]
阅读更多

关于【调用线程必须STA,因为许多 UI 组件需要】的问题 实在不知道怎么改了 贴出代码麻烦大神给改一下吧!

05-22

【背景介绍】:在网上下载了一个Html to RTF的源码,涉及到WPF。我的程序是winformrn在winform一个线程中调用如下代码rn[code=csharp]string a = HtmlToRtfConverter.ConvertHtmlToRtf(tvalue);[/code]rnConvertHtmlToRtf相关代码如下rn[code=csharp]rnpublic static string ConvertHtmlToRtf(string htmlText)rn rn var xamlText = HtmlToXamlConverter.ConvertHtmlToXaml(htmlText, false);rn rn return ConvertXamlToRtf(xamlText);rn rn rn private static string ConvertXamlToRtf(string xamlText)rn rn var richTextBox = new RichTextBox();//运行时此处报错,调用线程必须为 STA,因为许多 UI 组件都需要。rnrn if (string.IsNullOrEmpty(xamlText)) return "";rnrn var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);rnrn //Create a MemoryStream of the xaml contentrnrn using (var xamlMemoryStream = new MemoryStream())rn rn using (var xamlStreamWriter = new StreamWriter(xamlMemoryStream))rn rn xamlStreamWriter.Write(xamlText);rn xamlStreamWriter.Flush();rn xamlMemoryStream.Seek(0, SeekOrigin.Begin);rnrn //Load the MemoryStream into TextRange ranging from start to end of RichTextBox.rn textRange.Load(xamlMemoryStream, DataFormats.Xaml);rn rn rnrn using (var rtfMemoryStream = new MemoryStream())rn rnrn textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);rn textRange.Save(rtfMemoryStream, DataFormats.Rtf);rn rtfMemoryStream.Seek(0, SeekOrigin.Begin);rn using (var rtfStreamReader = new StreamReader(rtfMemoryStream))rn rn return rtfStreamReader.ReadToEnd();rn rn rnrn rn[/code]rn运行时提示 调用线程必须为 STA,因为许多 UI 组件都需要。rn在网上搜了这个问题是WPF的多线程的问题,可是对多线程了解的实在是太少,试了很长时间还是没解决这个问题。rnrn麻烦各位帮忙看下怎么修改呢?

没有更多推荐了,返回首页