Painting in a custom control and the invalidate mechanism - winforms

A custom control I am creating needs to draw many "items" in its client space. A call to Invalidate() would trigger a new paint cycle wherein all items would be redrawn.
Now when there are many items and a lot of navigation happens within the control, things need to be optimized; so I need to trigger a paint cycle where only one or two items are drawn. I store references to these items so that the paint method (OnPaint) knows it's a "quicky".
The difficulty is that when OnPaint is executed, it is hard to know if other Invalidate() calls have been made in the meantime. In that case it should do a "normal", complete paint.
I do make use of the clip rectangle. Of course I could check if the clip rectangle in OnPaint has become the whole of the client rectangle, a sign that Invalidate() was called, but this is not 100% safe. I thought of other similar solutions but they seem hacky.
What is the way this problem is usually, or best, solved?

The solution here would be to employ a double buffering approach with the BufferedGraphics class. This way you won't have so much tricky stuff going on in your OnPaint and you'll be able to paint whenever, whatever.
MSDN: Double Buffered Graphics (under "Manually Managing Buffered Graphics")
Here's a useful example:
Custom Drawing Controls in C# – Manual Double Buffering

Related

How to display render status in a WPF form?

I'm overriding WPF's OnRender to draw complex graphics. This may rarely take a long time. I would like to indicate to the user that the app did not crash, but is "merely" taking a long time to render.
How would I do that? It seems not possible to modify the UI in any way during the OnRender call.
You are talking about placing a "Busy Indicator" on top of your drawing.
Just place a half transparent grid on top with the writing "Loading..."
and you're done.
Bind its visibility to some bool that you update once when entering the complex rendering, and once when finished.
Or put a spinning Ellipse with gradient background if you want to see motion..
Since the OnRender method will execute on the UI thread you cannot do anything else such as displaying an interactive ProgressBar or respond to user input during the execution of your code.
What you can do is to pop up a new window that launches in a separate thread and display this one right before you begin to draw your complex graphics.
Please refer to my answer in the following similar question for more information about this.
Wait screen during rendering UIElement in WPF
Once the OnRender method has returned you then close the temporary "loading" window:
Can I stop WPF from executing UI actions out of the order in my code

OnRender not called after InvalidateVisual()

A custom WPF Control overrides OnRender. The method generates and displays a Path from custom data. The data provider is bound using a Dependency Property. The Dependency Property registers for an event when data changed. This event in turn calls InvalidateVisual().
However, after the InvalidateVisual() the OnRender is not always called.
We use the Prism Framework and the Region functionallity. The Control in question is embedded in such a Region, which is activated and deactivated. However, the Control's property "IsVisible" is true whenever the region is active. But still, when calling InvalidateVisual() the OnRender method is not called...
What could prevent the OnRender method from being called?
I just had this problem, too.
Context
I've got a load of controls based on the DynamicDataDisplay graph components inside a VirtualizingStackPanel (inside a ListBox).
When there are more controls that are visible at once, but not enough for the VirtualizingStackPanel to start re-using them when you scroll then I see this issue with the D3 AxisControl class. For some reason it does a lot of work in it's OnRender method, which it tries to trigger by calling InvalidateVisual when something changes.
In the problem case the problem controls call InvalidateVisual but they never get a call to MeasureOverride, ArrangeOverride or OnRender. Interestingly, most of the controls still work, in one particular problem case I get the last 3 out of a set of 11 failing to work properly. Notably those 3 (and only those 3) receive a call to MeasureOverride immediately before the data binding update that triggers the call to InvalidateVisual.
My Fix
In the end I managed to fix it by adding a call to InvalidateMeasure alongside the call to InvalidateVisual.
It's a horrible solution, but it's not a performance critical part of our application, so I seem to be getting away with it.
If the size of your control is staying the same, you should not be using InvalidateMeasure() or InvalidateVisual() because they trigger an expensive re-layout.
WPF is a retained drawing system. OnRender() might be better called AccumulateDrawingObjects(), because it doesn't actually draw. It accumulates a set of drawing objects which WPF uses to draw your UI whenever it wants. The magic thing is, if you put a DrawingGroup into the DrawingContext during OnRender(), you can actually efficiently update it after OnRender, anytime you like.
See my answer here for more details..
https://stackoverflow.com/a/44426783/519568
I just had this problem, too.
I had a scrollbar for a control which only figured out during OnRender() how much space is really needed to display all content, which could be bigger than the available display space and therefor needed a scrollbar. It could happen that OnRender() called some methods which ultimately changed the value of the scrollbar which was supposed to start OnRender() with InvalidateVisual().
However, OnRender() did not get called again after InvalidateVisual(). I guess the reason is that InvalidateVisual() sets some flags which tells WPF that the control needs to get drawn again, but once OnRender() finishes, that flag gets reset. Here some pseudo code how I expect it to happen:
//someCode:
control.InvalidateVisual()
//code of InvalidateVisual()
control.RedrawFlag = true;
//WPF some time later:
if (control.RedrawFlag){
control.OnRender()
//OnRender code
//do some stuff
//decide control needs to be redrawn
//however, RedrawFlag is alreday true!
//next line is not changing anything
control.RedrawFlag = true;
//WPF finished executing control.OnRender
control.RedrawFlag = false;
}
I didn't further investigate if WPF really works this way, but it would explain why OnRender() does not get called a second time.
Instead of wasting even more time, I changed how to calculate the total width of the control content can be and put this code outside of OnRender().

WPF Newbie question

I'm trying to learn WPF animations and am currently confused by quite a few things:
I used tools like processing, where you have a simple method which is called n times per minute, where n is the frame rate.
The way to do animations in WPF is to modify a property. If i use for example DoubleAnimation then a double is increased as the animation proceeds. But this is not exactly what I want. I want that in every cycle some properties are increased, some are modified by random and some are modified by user interaction. How can I do this in WPF?
What is also confusing me is the fact that WPF supports multiple animations at the same time. How does this work? Is there a thread for every animation or just one for all animations.
I used gdi with c# some time ago. I even could use multiple threads for drawing; As far as I remember I just had to insert all the drawing commands in some queue and then windows took care of them.. I have no idea how this is handled with WPF.
On a basic level, WPF animations are just the same as any other kind of animation: internally a timer ticks and some properties are modified which lead to a different picture when drawn to the screen.
WPF does all the leg work for you to be able to specify animations relative to wall-clock time, like "move that box at 3mm per second to the left". For more complex scenarios you might want to code up your own Animation, see the Custom Animation Overview article on the MSDN.
Regarding threading, WPF works the same as GDI: There is one Thread that handles all the interaction with the WPF model and you can only talk to WPF Controls if you're running on this thread. You can use the Dispatcher to "send" code to this thread if you are free threading. Actual drawing to DirectX is done in a separate thread, but that is of no concern to casual users of the API.
You can run several animations at the same time by putting them into a StoryBoard.
You can use the animation's BeginTime to get one animation to start after another.
You can use the key frames version (DoubleAnimationUsingKeyFrames) or the path version (DoubleAnimationUsingPath) to create complex non-linear animations.

Windows Forms Application Performance

My app has many controls on its surface, and more are added dynamically at runtime.
Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc).
What are your tips and tricks to improve WinForms app performance?
I know of two things you can do but they don't always apply to all situations.
You're going to get better performance if you're using absolute positioning for each control (myNewlyCreatedButton.Location.X/Y) as opposed to using a flow layout panel or a table layout panel. WinForms has to do a lot less math trying to figure out where controls should be placed.
If there is a single operation in which you're adding/removing/modifying a lot of controls, call "SuspendLayout()" on the container of the affected controls (whether it is a panel or the whole form), and when you're done with your work call "ResumeLayout()" on the same panel. If you don't, the form will have to do a layout pass each and every time you add/remove/modify a control, which cost a lot more time. see: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx
Although, I'm not sure how these approaches could apply when resizing a window.
Although more general than some of the other tips, here is mine:
When using a large number of "items", try to avoid creating a control for each one of them, rather reuse the controls. For example if you have 10 000 items, each corresponding to a button, it is very easy to (programatically) create a 10 000 buttons and wire up their event handlers, such that when you enter in the event handler, you know exactly which element you must work on. However it is much more efficient if you create, lets say, 500 buttons (because you know that only 500 buttons will be visible on the screen at any one time) and introduce a "mapping layer" between the buttons and the items, which dynamically reassigns the buttons to different items every time the user does something which would result in changing the set of buttons which should be visible (like moving a scrollbar for example).
Although, I'm not sure how these approaches could apply when resizing a window.
Handle the ResizeBegin and ResizeEnd events to call SuspendLayout() and ResumeLayout(). These events are only on the System.Windows.Form class (although I wish they were also on Control).
Are you making good use of SuspendLayout() and ResumeLayout()?
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx

So what am I missing with this here WPF?

Background: I have a little video playing app with a UI inspired by the venerable Sasami2k, just updated to use VMR9 (i.e. Direct3D9 with DirectShow) and be less unstable. Currently, it's a C++ app using raw Win32, through necessity: none of the various toolkits are worth a damn. WPF, in particular, was not possible, due to its airspace restrictions.
OK, so, now that D3DImage exists it might be viable to mix and match D3D/VMR9/DirectShow and WPF. Given past frustrations with Win32's inextensibility, this seems like a good thing.
But y'know, I'm falling at the first hurdle here.
With Win32 I have created (very easily) a borderless window that's resizable, resizes proportionately, snaps to the screen edges, and takes up the whole screen (including taskbar area) when maximized. It's a video app, so these are all pretty desirable properties.
OK, so, how to do the same with WPF?
In Win32, I use:
WM_GETMINMAXINFO to control the maximize behaviour
WM_NCHITTEST to control the resize borders
WM_MOVING to control the snap-to-screen-edges
WM_SIZING to control the resize aspect ratio
However, looking at WPF it seems that the various events arrive too late, unless I'm misunderstanding the documentation?
For example, I don't know when I'm mid-move, as LocationChanged says it fires only once the window has moved (which is too late).
Similarly, it appears that StateChanged only fires once the window has been restored/maximized (when I need the information prior to the maximize, to tell the system the correct maximize size).
And I seem to be completely overlooking where the system tells me about resizes. Likewise the hit testing.
So, uh, am I missing something here, or do I have no choice but to drop back to hooking the wndproc of this thing anyway? Can I do what I want without hooking the WndProc?
If I have to use the WndProc I might as well stick with my existing codebase; I want to have simpler, cleaner UI code, and moving away from the WndProc is fundamental to this.
If I do have to hook the WndProc, I have to wonder--why? Win32 has got the sizing/sized, moving/moved, poschanging/poschanged window messages, and they're all useful. Why wouldn't WPF replicate the same set of events? It seems like an unnecessary gap in functionality.
Plus, it means that WPF is tied to a specific USER32-dependent implementation. This means that MS can't (in Windows 7 or 8, say) invert the display layer to make WPF "native" and emulate HWNDs and WndProcs for legacy apps--even though this is precisely what MS should be doing.
OK, to answer my own question, I was missing Adorners (never came back in any of the searches I did, so it doesn't seem that they're as widely known as they perhaps should be).
They seem rather more complex than the WndProc overrides, unfortunately, but I think it should be possible to manhandle them into doing what I want.
And I seem to be completely overlooking where the system tells me about resizes. Likewise the hit testing.
For the resizing you're indeed missing the SizeChanged event.
AFAIK there is sadly no OnSizeChanging, OnLocationChanging and OnStateChanging event on a Window in .NET
I saw that one, but as far as I can tell it only fires after the size has changed, whereas I need the event to fire during the resize. Unless I'm misreading the docs and it
actually fires continuously?
It does not fire continuously but you can probably use the ResizeBegin and ResizeEnd events and be able to do that.
Aren't they WinForms events?
Hmm, you're right.
In code you can set the WindowStyle property to "None" and WindowsState to "Maximized"
Im not sure what the Xaml would look like.
Can you perhaps override the ArrangeOverride and/or MeasureOverride to make up for those missing resize events? Measure is the first pass, and occurs when a layout needs to adjust for a new size, so it's kind of like a size changing event.

Resources