c# - 标签在 ToolStrip 上方不可见

标签 c# winforms z-order

在运行时,我根据需要向主窗口添加(和删除)多个控件,该主窗口在设计器中仅包含带有一些功能按钮的 ToolStrip。在某些情况下,我想在 toolStrip 旁边添加信息标签,但我无法使其可见,即。它隐藏在下面。标签的代码很简单

infoLabel = new Label();
infoLabel.AutoSize = true;
infoLabel.Location = new System.Drawing.Point(200, 10);
infoLabel.Size = new System.Drawing.Size(35, 13);
infoLabel.BackColor = System.Drawing.SystemColors.Control;
infoLabel.Font = new System.Drawing.Font("Arial", 13);
infoLabel.ForeColor = System.Drawing.Color.Black;
infoLabel.TabIndex = 1;
infoLabel.Text = "this is info";
infoLabel.BringToFront();
this.Controls.Add(infoLabel);

TabIndexBringToFront 我添加作为绝望的行为,它没有帮助。顺便说一句,ToolStrip 的 TabIndex 是 2,它的 BackColor 我更改为透明。

但是,当我在设计器中的 ToolStrip 上放置标签时,它是可见的(即在顶部)。然后我分析了代码,但没有发现与我正在编写的内容有任何不同。我在这里缺少什么?

最佳答案

我建议在最后调用 infoLabel.BringToFront();,至少之后 this.Controls.Add(infoLabel);您当前的代码已修改:

infoLabel = new Label();
...
infoLabel.Text = "this is info";

// First Add to this
this.Controls.Add(infoLabel);

// Only then we can make infoLabel be the topmost 
// among all existing controls which are on this
infoLabel.BringToFront();

我们创建 infoLabel,将其添加到 this 并最终使其位于 this 上的最上面。为了使代码更具可读性,我建议如下:

// Create a label on this
infoLabel = new Label() {
  AutoSize  = true,
  Location  = new System.Drawing.Point(200, 10),
  Size      = new System.Drawing.Size(35, 13),
  BackColor = System.Drawing.SystemColors.Control,
  Font      = new System.Drawing.Font("Arial", 13),
  ForeColor = System.Drawing.Color.Black,
  TabIndex  = 1,
  Text      = "this is info",
  Parent    = this // <- instead of this.Controls.Add(infoLabel);
};

// make infoLabel topmost among all controls on this
infoLabel.BringToFront();

关于c# - 标签在 ToolStrip 上方不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59393922/

相关文章:

c# - 二维深度系统方法 XNA C#

windows - wxPython:使框架位于一切之上

c# - 在 Windows Phone 运行时更改图像控件的 z 顺序

c# - 特殊文件夹

c# - 隐藏 ListViewItem 而不是删除它?

c# - Microsoft Azure Functions Nuget 包阻止 NET 库打包到 Nuget 中

c# - 找不到适合指定区域性的任何资源(资源文件中的 C# WinForm 图像)

c# - Visual Studio 在运行程序后向 DataGridView 添加列

c# - ADO.NET 需要 >5 秒才能以 ASP.NET 形式打开 MySql 连接

c# - AssemblyResolve 事件在调用 Assembly.Load(byte()) 时触发