带有 Windows 窗体的 WPF - STAThread
我是 WPF 的新手,有几个关于 WPF 和 Windows 窗体集成的问题。
我有一个现有的 Visual C# Windows 窗体应用程序。 我想将它与 WPF 窗口集成,单击按钮即可显示该窗口。 这是不可能的,因为 WPF 期望调用线程是 STAThread,并且默认情况下 WinForm 假定该线程是 MTAThread。 我尝试生成一个单元状态为 STAThread 的新线程来调用 WPF UI,但这不起作用。 我也尝试使用 Dispatcher.BeginInvoke 方法和后台工作程序,但它们都没有解决问题。
1) 我们可以在不将 Main 标记为 STAThread 的情况下调用 WPF 窗口/控件吗? 如果可能的话,有人可以指出我正确的方向吗? 2) 如果实现此目的的唯一方法是将主线程设置为 STAThread,是否会对应用程序的总体性能/响应能力产生影响。
提前致谢。
I am a newbie to WPF and have a couple of questions about WPF and Windows Forms integration.
I have an existing Visual C# Windows Forms application. I would like to integrate it with a WPF window, that can be shown on a button click. This was not possible as WPF expects the calling thread to be a STAThread and by default WinForm assumes that the thread is an MTAThread. I tried spawning a new thread with an apartment state of STAThread for calling the WPF UI but that did not work. I tried using the Dispatcher.BeginInvoke method and Background Worker as well, but none of them resolved the issue.
1) Can we make a call to WPF window/control without marking the Main as an STAThread? If it is possible, Can anyone please point me to a proper direction?
2) If the only way to accomplish this is by making the Main Thread an STAThread, will there be any impact to the general performance/responsiveness of the application.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为最简单的解决方案是让 WinForms 线程在 STA 中执行。 拥有一个 STA 线程 winforms 应用程序并没有什么问题(事实上它通常是默认的)。
您可以通过将以下行添加到程序的 main 方法来解决此问题:
I think the simplest solution is to make your WinForms thread execute in an STA. There is nothing wrong with having an STA thread winforms app (it is in fact often the default).
You can fix this by adding the following line to the main method of your program: