1

In my WPF application, I have added WindowsFormsHost in one grid, I want to draw a rectangle on the control inside WinFormsHost.

Application layout:

Application Layout Image

Code I'm trying:

Adorner Class

public class SimpleRectAdorner : Adorner
    {
        // Be sure to call the base class constructor.
        public SimpleRectAdorner(UIElement adornedElement)
          : base(adornedElement)
        {
        }

        // A common way to implement an adorner's rendering behavior is to override the OnRender
        // method, which is called by the layout system as part of a rendering pass.
        protected override void OnRender(DrawingContext drawingContext)
        {
            Rect adornedElementRect = new Rect(this.AdornedElement.DesiredSize);

            // Some arbitrary drawing implements.
            SolidColorBrush renderBrush = new SolidColorBrush(Colors.Green);
            renderBrush.Opacity = 0.2;
            Pen renderPen = new Pen(new SolidColorBrush(Colors.Navy), 1.5);

            // Draw a circle at each corner.
            Rect rect = new Rect(new Point(adornedElementRect.TopLeft.X, adornedElementRect.TopLeft.Y + 50), new Size(150, 50));
            drawingContext.DrawRectangle(renderBrush, renderPen, rect);
        }
    }

Code to add adorner

 private void btnDraw_Click(object sender, RoutedEventArgs e)
        {
            AdornerLayer.GetAdornerLayer(viewerGrid.Children[0]).Add(new SimpleRectAdorner(viewerGrid.Children[0]));
        }

Is there any possible way to draw a rectangle on Control which is inside WindowsFormsHost?

Thanks in advance.

KishanRSojitra
  • 267
  • 3
  • 17

1 Answers1

0

As noted in the comment by Clemens, WindowsFormsHost is rendered separately from the rest of your Window, and by necessity it is rendered on top of the Window. At first glance, this seems to be a design limitation about which you can do nothing; however, that is not strictly true.

If a second layer is added over your first layer, simply add a third layer on top of the second. Another Window or a Popup can render over the top of your WindowsFormsHost, and while you will have to jump through some hoops to make it all seem like part of the same Window--ensuring everything moves, minimizes, and restores at the same time, etc--it is certainly possible to do so.

You can use transparency in your third layer to allow the content in the WindowsFormsHost to show and be accessed. For example, you can set AllowsTransparency to true on your WPF Popup. It will be a bit of extra work, but if you absolutely need this feature, you can do it.

Daniel
  • 582
  • 8
  • 15