How to set Z-order of a Control using WinForms

只谈情不闲聊 提交于 2019-11-26 17:53:56

Call the GetChildIndex and SetChildIndex methods of the parent's Controls collection.

There is no Z-order as there was in VB, but you can use the GetChildIndex and SetChildIndex methods to get and set their indexes manually.

Here there's an example of how to use it. You will probably need to keep a record of each controls index though so you can set it back to it when it's finished with.

Something like this is probably what you're after:

// Get the controls index
int zIndex = parentControl.Controls.GetChildIndex(textBox);
// Bring it to the front
textBox.BringToFront();
// Do something...
// Then send it back again
parentControl.Controls.SetChildIndex(textBox, zIndex);

When used with the FlowLayoutPanel this will move a control up or down

    /// <summary>
    /// When used with the FlowLayoutPanel this will move a control up or down
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="UpDown"></param>
    private void C_On_Move(object sender, int UpDown)
    {
        //If UpDown = 1 Move UP, If UpDown = 0 Move DOWN
        Control c = (Control)sender;
        // Get the controls index
        int zIndex = _flowLayoutPanel1.Controls.GetChildIndex(c);
        if (UpDown==1 && zIndex > 0)
        {
            // Move up one
            _flowLayoutPanel1.Controls.SetChildIndex(c, zIndex - 1);
        }
        if (UpDown == 0 && zIndex < _flowLayoutPanel1.Controls.Count-1)
        {
            // Move down one
            _flowLayoutPanel1.Controls.SetChildIndex(c, zIndex + 1);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!