Question

I have a UserControl that adds other UserControls, but I want the "latest" control added to be topmost so it's above the others. Because the controls should be overlapping eachother. Like a card game. So I add 5 controls, the first one should have the least priority the latest the most priority - most visible.

Any ideas?

Or do I have to override the Paint method for the "container" control? And Control.CreateGraphics() and draw it?

Was it helpful?

Solution

Consider BringToFront and SendToBack methods of the Control class. Check out answers to these questions too

How to set Z-order of a Control using WinForms

Bring Winforms control to front

OTHER TIPS

Just use userControl1.BringToFront() when you add the new control.

Note however, that won't prevent the user from "tabbing" into the controls that are underneath it. For that, you need to disable or make invisible the other controls.

In Windows Forms, the order in which controls are added to their parents' Controls collection determines the order of their rendering.

This means that either you handle the addition of child controls in code and use the appropriate insert positions, or you move the controls around in the designer (which, unfortunately, often means dangerous hand edits to the *.Designer.cs file).

I recommend that you go for the first approach, which is the only feasible method for larger WinForms projects anyway, and make the control insertion logic explicit in your code. The good news, by the way, is that there is no need to tinker with paint handlers, so your worry about hacks like using CreateGraphics() is unjustified and dispelled :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top