Custom Paint handler on a WinForms Control inside a WPF application

人走茶凉 提交于 2019-12-08 06:09:30

问题


I have a WPF application with a Windows Form element hosted inside it, using this method:

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);

However, I'm having problems trying to add a custom Paint event handler to it. It seems that adding it in WPF (not shown here) causes the drawing to be done beneath the WinForm control, so nothing appears on top. Adding it to the WinForm control does nothing whatsoever; the paint event (gMapZoom_Paint) is never even called.

Any help would be much appreciated.


回答1:


You can add a PaintEventHandler event to your Windows Form Control (gMapZoom)

 public event PaintEventHandler OnPaint;

 public GMap()
 {
   InitializeComponent();
   this.Paint += new PaintEventHandler(GMap_Paint);
 }

 void Gmap_Paint(object sender, PaintEventArgs e)
 {
     OnPaint(this, e);
 }

In WPF code behind:

{
  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         
}

Then you can trigger the OnPaint event by:

gmap.Invalidate();


来源:https://stackoverflow.com/questions/9198298/custom-paint-handler-on-a-winforms-control-inside-a-wpf-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!