如何将WinForms表单的所有者正确设置为WPF窗口? [英] How do I properly set the owner of a WinForms form to a WPF Window?

查看:103
本文介绍了如何将WinForms表单的所有者正确设置为WPF窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将WinForms表单的所有者设置为WPF窗口:

I'm in a situation where I need to set a WinForms form's owner to a WPF window:

WindowInteropHelper h = new WindowInteropHelper(owner);
SetParent(form.Handle, h.Handle);

System.Windows.Forms.DialogResult dialogResult = form.ShowDialog();





当我运行代码,它打破了对ShowDialog的调用。为什么会这样?这是在WPF应用程序的Dispatcher上运行,以使其线程安全,因为在此程序中有许多异步进程正在运行。我使用P / Invoke从user32.dll导入SetParent函数。



When I run the code, it breaks in the call to ShowDialog. Why would this be? This is being run on the WPF Application's Dispatcher to make it thread safe since there are many async processes running amok in this program. I have used P/Invoke to import the SetParent function from user32.dll.

推荐答案

不要混淆父子关系和所有者拥有的表单/窗口。表格和窗户不应该是儿童,但所有权是您真正需要使用的重要关系。

请参阅:

表格:

http://msdn.microsoft.com/en -us / library / system.windows.forms.form.owner(v = vs.110).aspx [ ^ ],

http://msdn.microsoft.com/en-us/ library / system.windows.forms.form.addownedform(v = vs.110).aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/s ystem.windows.forms.form.ownedforms(v = vs.110).aspx [ ^ ];

WPF:

http://msdn.microsoft.com/en -us / library / system.windows.window.owner(v = vs.110).aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.windows。 window.ownedwindows(v = vs.110).aspx [ ^ ]。



注意属性所有者是读写的,所以你可以简单地分配主人。



我希望,如果你问这个问题,你就知道为什么所有权很重要。通常,窗体的主窗口成为所有其他窗口/窗体的所有者(我不计算模态窗口/窗体)。如果您对此有疑虑,欢迎提出您的后续问题,但是......请先询问,创建一些窗口和一些表格,建立所有权,玩这样的应用程序,自己看看差异。



-SA
Don't mix up parent-child relationship and owner-owned form/window. Forms and windows should not be children, but ownership is important relationship you really need to use.
Please see:
Forms:
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.owner(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.addownedform(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.ownedforms(v=vs.110).aspx[^];
WPF:
http://msdn.microsoft.com/en-us/library/system.windows.window.owner(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.window.ownedwindows(v=vs.110).aspx[^].

Note that the property Owner is read-write one, so you can simply assign the owner.

I hope, if you ask this question, you know why ownership is important. Typically, main window of form becomes an owner of all other windows/forms (I don't count modal windows/forms here). If you have concerns about that, your follow-up questions will be welcome, but… please, before asking, create some windows and some forms, establish ownership, play with such application, to see the difference by yourself.

—SA


这篇关于如何将WinForms表单的所有者正确设置为WPF窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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