【问题标题】:How to set Z-order of a Control using WinForms如何使用 WinForms 设置控件的 Z 顺序
【发布时间】:2011-03-13 21:34:45
【问题描述】:

我正在编写一个自定义TextBox,它在获得焦点后会改变其边框样式。

由于添加边框会导致控件与相邻的控件重叠,因此我暂时将文本框置于对话框的前面(使用textBox.BringToFront())。

但是,一旦编辑完成并且失去焦点,我想将控件发送回其在 Z 顺序中的原始位置。

这可能吗(最好以简单的方式!)

【问题讨论】:

    标签: c# winforms textbox focus z-order


    【解决方案1】:

    调用父级的Controls 集合的GetChildIndexSetChildIndex 方法。

    【讨论】:

    • 太棒了——BringToFront() 误入歧途 我在错误的地方寻找这些方法:查看控件的方法,而不是父控件的方法。谢谢。
    • 不用举例,自己回答就够了!
    • 来自参考:“索引值为 0 的控件位于 z 顺序的顶部,数字越大越靠近底部。”
    • 有趣的是,如果控件的父级不为空,BringToFront() 依赖于 SetChildIndex()
    【解决方案2】:

    没有像 VB 中那样的 Z 顺序,但您可以使用 GetChildIndexSetChildIndex 方法手动获取和设置它们的索引。

    Here 有一个如何使用它的例子。不过,您可能需要记录每个控件索引,以便在完成后将其设置回它。

    这样的东西可能就是你所追求的:

    // 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);
    

    【讨论】:

    • 当您动态地使控件(不)可见时,一切都会发生变化。设置'textbox.Visible = true',它的索引为0。它完全忽略了文档大纲中的顺序。我花了一段时间才弄清楚:)
    • 也试图解决这个问题。这条评论帮助了我。谢谢
    【解决方案3】:

    当与 FlowLayoutPanel 一起使用时,这将向上或向下移动控件

        /// <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);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 2010-11-05
      • 1970-01-01
      • 2011-02-06
      • 2023-02-02
      相关资源
      最近更新 更多