【问题标题】:Custom Paint handler on a WinForms Control inside a WPF applicationWPF 应用程序内 WinForms 控件上的自定义绘制处理程序
【发布时间】:2012-02-09 04:09:58
【问题描述】:

我有一个 WPF 应用程序,其中托管了一个 Windows 窗体元素,使用此方法:

System.Windows.Forms.Integration.WindowsFormsHost host =
    new System.Windows.Forms.Integration.WindowsFormsHost();

gMapZoom = new GMap();
gMapZoom.Paint += new PaintEventHandler(gMapZoom_Paint);
host.Child = gMapZoom; // gMapZoom is the Windows Form control
// Add the interop host control to the Grid
// control's collection of child controls.
this.grid1.Children.Add(host);

但是,我在尝试向其添加自定义 Paint 事件处理程序时遇到问题。似乎在 WPF 中添加它(此处未显示)会导致绘图在 WinForm 控件下方完成,因此顶部不会出现任何内容。将它添加到 WinForm 控件中没有任何作用;绘制事件 (gMapZoom_Paint) 甚至从未被调用过。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# .net wpf winforms paint


    【解决方案1】:

    您可以将 PaintEventHandler 事件添加到您的 Windows 窗体控件 (gMapZoom)

     public event PaintEventHandler OnPaint;
    
     public GMap()
     {
       InitializeComponent();
       this.Paint += new PaintEventHandler(GMap_Paint);
     }
    
     void Gmap_Paint(object sender, PaintEventArgs e)
     {
         OnPaint(this, e);
     }
    

    在 WPF 代码后面:

    {
      System.Windows.Forms.Integration.WindowsFormsHost host =
                    new System.Windows.Forms.Integration.WindowsFormsHost();
    
      gmap = new GMap();
      gmap.OnPaint += new System.Windows.Forms.PaintEventHandler(gmap_Paint);
      host.Child = gmap;
      this.grid1.Children.Add(host);
     }
    
    void gmap_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {
      //Custom paint         
    }
    

    然后您可以通过以下方式触发 OnPaint 事件:

    gmap.Invalidate();
    

    【讨论】:

    • 这并没有真正的帮助..这就是我已经在做的事情。问题是绘制事件永远不会被调用。就像,在你的例子中, GMap_Paint 永远不会被执行。
    • 这是我的意思的一个示例:pastebin.com/HEqW08Rs 在该示例中,pictureBox_Paint 方法在应用程序首次加载时被调用一次。之后,即使调用 Invalidate(),它也不会重新绘制。
    • 嗯...我已经让答案更清楚了。它在我的沙箱中运行。
    • 我发现了我的问题:Invalidate() 从一开始就没有被调用过。结果表明您放入的任何事件处理程序都必须是 WinForms 控件的处理程序,而不是包含它的 WPF 控件。所以在我上面的例子中,我必须将事件处理程序添加到pictureBox,而不是grid1。谢谢你的帮助! :)
    猜你喜欢
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    相关资源
    最近更新 更多