【问题标题】:WPF & WinForms Integration and Application ClassWPF & WinForms 集成及应用类
【发布时间】:2010-01-08 00:51:44
【问题描述】:

我打算创建一个带有主窗口的 WPF 应用程序,它可以启动各种 WinForms。一些 WinForms 使用 System.Windows.Forms.Application 类(DoEvents、Application.Path 等)。你觉得这样做会有问题吗?

我还能从 WPF 应用程序启动的 WinForm 中使用 System.Windows.Forms.Application.DoEvents() 吗?

【问题讨论】:

  • 你为什么要这样做?您有想要重复使用的旧表单吗?​​
  • 是的,我有一个相当大的应用程序,我需要同时使用这两种技术,直到我可以将所有表单都转换为 WPF。

标签: wpf winforms


【解决方案1】:

主要问题在于能否实例化 Windows 窗体窗口并将其所有者设置为 WPF 窗口的所有者。 Winforms 需要一个 IWin32Window,而 WPF 窗口不是。要解决这个问题,您需要创建一个自定义类。

我在 Mark Rendle 的博客上找到了这段代码(我在这里复制了它,因为我必须使用 Google 缓存来访问该页面)。 LINK - 警告:可能不起作用

class Shim : IWin32Window
{
  public Shim(System.Windows.Window owner)
  {
    // Create a WindowInteropHelper for the WPF Window
    interopHelper = new WindowInteropHelper(owner);
  }

  private WindowInteropHelper interopHelper;

  #region IWin32Window Members

  public IntPtr Handle
  {
    get
    {
      // Return the surrogate handle
      return interopHelper.Handle;
    }
  }

  #endregion
}

以及它的使用方法:

namespace System.Windows.Forms
{
  public static class WPFInteropExtensions
  {
    public static DialogResult ShowDialog(
        this System.Windows.Forms.Form form,
        System.Windows.Window owner)
    {
      Shim shim = new Shim(owner);
      return form.ShowDialog(shim);
    }
  }
}

我还没有测试过这段代码,但是在互联网上阅读,看来您可以在 WPF 应用程序中托管 Winforms 窗口。

我刚刚在 MSDN 上找到了 this 链接,该链接非常详细地描述了如何在 WPF 应用程序中互操作 Win32 控件/窗口。

希望这些对您有所帮助。

【讨论】:

  • 感谢您提供的好信息。我想我现在的问题是我还能从 WPF 应用程序启动的 WinForm 中使用 Application.DoEvents() 吗?
  • 无论如何你都不应该使用 Application.DoEvents()。codinghorror.com/blog/archives/000159.html,但如果你必须这样做,我真的说不出会发生什么。
  • 我同意我需要远离 DoEvents,但这个应用程序最初是在 .net 之前编写的,它无处不在。
  • Bleh,我为你感到难过。正如我所说,我真的不确定 DoEvents 将如何与互操作一起工作。
  • 我可能只是通过 UI 并替换它。我宁愿花一点时间摆脱它,也不愿产生一些奇怪的副作用。
【解决方案2】:

我有时会这样做,但没有遇到任何问题。 但是我并不真正推荐它,当您在 WPF 应用程序中时,您应该更喜欢 WPF。

例如,如果您想要应用程序路径,请使用: System.Reflection.Assembly.GetExecutingAssembly().Location

【讨论】:

    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 2013-03-04
    • 2017-08-19
    相关资源
    最近更新 更多