Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when a control (or window) has been rendered (drawn) in WPF?

I need to store the content of a Window into an image, save it and close the window. If I close the window on the Loaded event the image contains the Window with some items are drawn ok, some others are only half drawn or distorted while others are not on the image.

If I put a timer and close the window after a certain amount of time (something between 250ms and 1sec depending on the complexity of the window) the images are all ok.

Looks like the window needs some time to completely render itself. Is there a way to know when this rendering has been done to avoid using a Timer and closing the window when we know it has completed its rendering?

Thanks.

like image 211
Ignacio Soler Garcia Avatar asked Dec 09 '22 00:12

Ignacio Soler Garcia


2 Answers

I think you are looking for the ContentRendered event

like image 164
Dtex Avatar answered Dec 11 '22 12:12

Dtex


I had the similar problem in the application I am working, I solved it by using following code, try it and let me know if it helps.

 using (new HwndSource(new HwndSourceParameters())
                   {
                       RootVisual =
                           (VisualTreeHelper.GetParent(objToBeRendered) == null
                                ? objToBeRendered
                                : null)
                   })
        {
            // Flush the dispatcher queue
            objToBeRendered.Dispatcher.Invoke(DispatcherPriority.SystemIdle, new Action(() => { }));

            var renderBitmap = new RenderTargetBitmap(requiredWidth, requiredHeight,
                                                      96d*requiredWidth/actualWidth, 96d*requiredHeight/actualHeight,
                                                      PixelFormats.Default);

            renderBitmap.Render(objToBeRendered);
            renderBitmap.Freeze();                

            return renderBitmap;
        }
like image 31
Pank Avatar answered Dec 11 '22 12:12

Pank