如何:定义停靠的 ToolStrip 控件的 Z 顺序

若要通过停靠正确定位 ToolStrip 控件,则必须在窗体的 z 顺序中正确定位该控件。

示例

下面的代码示例演示如何通过指定 z 顺序排列 ToolStrip 控件和停靠的 MenuStrip 控件。

public Form2()
{
    // Create a new ToolStrip control.
    ToolStrip ts = new ToolStrip();

    // Populate the ToolStrip control.
    ts.Items.Add("Apples");
    ts.Items.Add("Oranges");
    ts.Items.Add("Pears");
    ts.Items.Add(
        "Change Colors",
        null,
        new EventHandler(ChangeColors_Click));

    // Create a new MenuStrip.
    MenuStrip ms = new MenuStrip();

    // Dock the MenuStrip control to the top of the form.
    ms.Dock = DockStyle.Top;

    // Add the top-level menu items.
    ms.Items.Add("File");
    ms.Items.Add("Edit");
    ms.Items.Add("View");
    ms.Items.Add("Window");

    // Add the ToolStrip to Controls collection.
    this.Controls.Add(ts);

    // Add the MenuStrip control last.
    // This is important for correct placement in the z-order.
    this.Controls.Add(ms);
}
Class Form2
   Inherits Form
   
   Public Sub New()
      ' Create a new ToolStrip control.
      Dim ts As New ToolStrip()
      
      ' Populate the ToolStrip control.
      ts.Items.Add("Apples")
      ts.Items.Add("Oranges")
      ts.Items.Add("Pears")
      ts.Items.Add("Change Colors", Nothing, New EventHandler(AddressOf ChangeColors_Click))
      
      ' Create a new MenuStrip.
      Dim ms As New MenuStrip()

      ' Dock the MenuStrip control to the top of the form.
      ms.Dock = DockStyle.Top
      
      ' Add the top-level menu items.
      ms.Items.Add("File")
      ms.Items.Add("Edit")
      ms.Items.Add("View")
      ms.Items.Add("Window")
      
      ' Add the ToolStrip to Controls collection.
      Me.Controls.Add(ts)
      
      ' Add the MenuStrip control last.
      ' This is important for correct placement in the z-order.
      Me.Controls.Add(ms)
    End Sub
   
   ' This event handler is invoked when the "Change colors"
   ' ToolStripItem is clicked. It assigns the Renderer
   ' property for the ToolStrip control.
    Sub ChangeColors_Click(ByVal sender As Object, ByVal e As EventArgs)
        ToolStripManager.Renderer = New ToolStripProfessionalRenderer(New CustomProfessionalColors())
    End Sub
End Class

z 顺序由 ToolStripMenuStrip

控件添加到窗体的 Controls 集合的顺序决定。

// Add the ToolStrip to Controls collection.
this.Controls.Add(ts);

// Add the MenuStrip control last.
// This is important for correct placement in the z-order.
this.Controls.Add(ms);
' Add the ToolStrip to Controls collection.
Me.Controls.Add(ts)

' Add the MenuStrip control last.
' This is important for correct placement in the z-order.
Me.Controls.Add(ms)

颠倒 Add 方法的调用顺序,查看对布局产生的影响。

编译代码

此示例需要:

  • 对 System.Design、System.Drawing 和 System.Windows.Forms 程序集的引用。

另请参阅