创建一个表单,并在后台线程使用Form.ShowDialog [英] Creating a Form and using Form.ShowDialog on a background thread

查看:148
本文介绍了创建一个表单,并在后台线程使用Form.ShowDialog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用的WinForms,
。如果我在一个线程,是不是主UI线程我safetly

Using Winforms, If I'm on a thread that is not the "main" ui thread can I safetly


  1. 创建一个表单,

  2. 在该表格上调用的ShowDialog

好像我是遵守的规则:
WinForms控件必须在他们创建的线程上修改

It seems like I would be obeying the rule of: Winforms controls must be modified on the thread they were created in.

从一些阅读我所做的好像的ShowDialog将创建自己的消息泵,这样我就不用担心上已经有一个消息泵线程创建的表格。

From some of the reading I've done it seems like ShowDialog will create its own message pump so that I don't need to worry about the Form being created on a thread that already has a message pump.

问题的背景是,我得到一个回调,我想展示一些的WinForms用户界面,但我没有访问,我可以用它来调用主线程其他UI。

The background of the question is that I get a callback where I'd like to display some Winforms UI, but I don't have access to any other UI that I could use to Invoke to the main thread.

推荐答案

这是正确的粗略,尽管这是你调用线程的SetApartmentState()方法的线程切换到STA非常重要的。重要的是许多UI操作,包括剪贴板,鼠标拖放及外壳的对话框。而且,你通常有一个糟糕Z顺序的问题时,你的线程上创建窗体不是在前台和背后隐藏的另一个窗口。或者有令人讨厌的习惯实际上的举动的时候,用户不希望它抢点击鼠标或意外击键前景。

That's roughly correct, albeit that it is pretty important that you call the thread's SetApartmentState() method to switch the thread to STA. Important for many UI operations, including the clipboard, drag and drop and the shell dialogs. And that you usually have a crummy Z-order problem when the form that you create on the thread is not in the foreground and hides behind another window. Or has the nasty habit of actually do move in the foreground when the user doesn't expect it and grab a mouse click or keystroke unexpectedly.

这是硬性的问题解决,他们也使您的应用程序片状。有没有很好的理由,没有一个参考要调用,你也可以将它传递给类某种程度上一些如何。你总是有Application.OpenForms [0],如果真的有必要依傍。

These are hard problems to fix, they do make your app flaky. There's no good reason to not have a reference to invoke to, you can also pass it to the class some way some how. You've always got Application.OpenForms[0] to fall back on, if really necessary.

这篇关于创建一个表单,并在后台线程使用Form.ShowDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆