Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Z-Index" in winforms

In CSS, we have a Property called z-index, what is the same in Winfrom set for a Panel control to the "Z-Index?

like image 887
eriksv88 Avatar asked Apr 14 '10 22:04

eriksv88


People also ask

What is Z index in C#?

The z-index CSS property sets the z-order of a positioned element and its descendants or flex items. Overlapping elements with a larger z-index cover those with a smaller one.

What is Z-order in Windows?

Z-Order. The z-order of a window indicates the window's position in a stack of overlapping windows. This window stack is oriented along an imaginary axis, the z-axis, extending outward from the screen. The window at the top of the z-order overlaps all other windows.

Will WinForms be deprecated?

WinForms won't be deprecated until Win32 is ... which could be quite sometime! WPF on the other hand has few direct dependencies on Win32 so could potentially form the basis of a "fresh start" UI layer on a future version of windows.


1 Answers

WinForms has a z-order, but you can't access it as a number. Instead, every control has a BringToFront method and a SendToBack method, which move the control to the top of the z-order or to the bottom, respectively.

Not sure exactly why it was exposed this way, although you rarely encounter situations where either BringToFront or SendToBack don't provide what you need.

Update: I'm wrong, you can access the z-order directly via a method on the control's container's Controls collection. Here's a simple method that wraps it:

public void SetControlZOrder(Control ctrl, int z)
{
    ctrl.Parent.Controls.SetChildIndex(ctrl, z);
}

I'm guessing they encapsulated this in BringToFront and SendToBack just to keep everything simple and easy to use. I applaud.

Update 2: I interpreted your comments to a different answer here to mean that you want to be able to take a control that is inside a panel and larger than the panel (so that part of it is hidden) and make it so that the control is in front of the panel and larger than it (so that you see the whole control).

You can do this by removing the control from the panel, shifting its position by the original panel's position, and adding it to the form's controls:

panel1.Controls.Remove(button1);
button1.Left += panel1.Left;
button1.Top += panel1.Top; 
this.Controls.Add(button1);

The Left and Top shifts are necessary because the button's position was originally relative to the panel, and will now be relative to the form. The shifts keep it in the original virtual position, so it appears to come out of the panel.

You would then have to deal with putting it back in the panel, which is just a reverse of the above code.

like image 108
MusiGenesis Avatar answered Sep 23 '22 03:09

MusiGenesis