ToolStripManager 클래스

정의

ToolStrip 렌더링 및 래프팅(rafting)과 MenuStrip, ToolStripDropDownMenuToolStripMenuItem 개체의 병합을 제어합니다. 이 클래스는 상속될 수 없습니다.

public ref class ToolStripManager sealed
public ref class ToolStripManager abstract sealed
public sealed class ToolStripManager
public static class ToolStripManager
type ToolStripManager = class
Public NotInheritable Class ToolStripManager
Public Class ToolStripManager
상속
ToolStripManager

예제

다음 코드 예제에서는 메뉴 항목 병합의 모든 일반적인 시나리오를 보여 줍니다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

public enum MergeSample
{
    None,
    Append,
    InsertInSameLocation,
    InsertInSameLocationPreservingOrder,
    ReplacingItems,
    MatchOnly
}
public class Form1 : Form
{
    ContextMenuStrip cmsBase;
    ContextMenuStrip cmsItemsToMerge;

    public Form1()
    {
        InitializeComponent();

        components ??= new Container();
        cmsBase = new ContextMenuStrip(components);
        cmsItemsToMerge = new ContextMenuStrip(components);

        // cmsBase is the base ContextMenuStrip.
        cmsBase.Items.Add("one");
        cmsBase.Items.Add("two");
        cmsBase.Items.Add("three");
        cmsBase.Items.Add("four");

        // cmsItemsToMerge contains the items to merge.
        cmsItemsToMerge.Items.Add("one");
        cmsItemsToMerge.Items.Add("two");
        cmsItemsToMerge.Items.Add("three");
        cmsItemsToMerge.Items.Add("four");

        // Distinguish the merged items by setting the shortcut display string.
        foreach (ToolStripMenuItem tsmi in cmsItemsToMerge.Items)
        {
            tsmi.ShortcutKeyDisplayString = "Merged Item";
        }
        // Associate the ContextMenuStrip with the form so that it displays when
        // the user clicks the right mouse button.
        this.ContextMenuStrip = cmsBase;

        CreateCombo();
    }

    #region ComboBox switching code.
    private void CreateCombo()
    {
        // This ComboBox allows the user to switch between the samples.
        ComboBox sampleSelectorCombo = new ComboBox();
        sampleSelectorCombo.DataSource = Enum.GetValues(typeof(MergeSample));
        sampleSelectorCombo.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
        sampleSelectorCombo.Dock = DockStyle.Top;
        this.Controls.Add(sampleSelectorCombo);

        TextBox textBox = new TextBox();
        textBox.Multiline = true;
        textBox.Dock = DockStyle.Left;
        textBox.DataBindings.Add("Text", this, "ScenarioText");
        textBox.ReadOnly = true;
        textBox.Width = 150;
        this.Controls.Add(textBox);
        this.BackColor = ProfessionalColors.MenuStripGradientBegin;
        this.Text = "Right click under selection.";
    }
    void comboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox sampleSelectorCombo = sender as ComboBox;
        if (sampleSelectorCombo.SelectedValue != null)
        {
            CurrentSample = (MergeSample)sampleSelectorCombo.SelectedValue;
        }
    }

    private string scenarioText;

    public string ScenarioText
    {
        get { return scenarioText; }
        set
        {
            scenarioText = value;
            if (ScenarioTextChanged != null)
            {
                ScenarioTextChanged(this, EventArgs.Empty);
            }
        }
    }

    public event EventHandler ScenarioTextChanged;

    #endregion

    private void RebuildItemsToMerge()
    {
        // This handles cases where the items collection changes for the sample.
        cmsItemsToMerge.SuspendLayout();
        cmsItemsToMerge.Items.Clear();
        cmsItemsToMerge.Items.Add("one");
        cmsItemsToMerge.Items.Add("two");
        cmsItemsToMerge.Items.Add("three");
        cmsItemsToMerge.Items.Add("four");
        // Distinguish the merged items by setting the shortcut display string.
        foreach (ToolStripMenuItem tsmi in cmsItemsToMerge.Items)
        {
            tsmi.ShortcutKeyDisplayString = "Merged Item";
        }
        cmsItemsToMerge.ResumeLayout();
    }
    #region Switching current samples.
    private MergeSample currentSample = MergeSample.None;
    private MergeSample CurrentSample
    {
        get { return currentSample; }
        set
        {
            if (currentSample != value)
            {
                bool resetRequired = false;

                if (currentSample == MergeSample.MatchOnly)
                {
                    resetRequired = true;
                }
                currentSample = value;
                // Undo previous merge, if any.
                ToolStripManager.RevertMerge(cmsBase, cmsItemsToMerge);
                if (resetRequired)
                {
                    RebuildItemsToMerge();
                }

                switch (currentSample)
                {
                    case MergeSample.None:
                        return;
                    case MergeSample.Append:
                        ScenarioText = "This sample adds items to the end of the list using MergeAction.Append.\r\n\r\nThis is the default setting for MergeAction. A typical scenario is adding menu items to the end of the menu when some part of the program is activated.";
                        ShowAppendSample();
                        break;
                    case MergeSample.InsertInSameLocation:
                        ScenarioText = "This sample adds items to the middle of the list using MergeAction.Insert.\r\n\r\nNotice here how the items are added in reverse order: four, three, two, one. This is because they all have the same merge index.\r\n\r\nA typical scenario is adding menu items to the middle or beginning of the menu when some part of the program is activated. ";
                        ShowInsertInSameLocationSample();
                        break;
                    case MergeSample.InsertInSameLocationPreservingOrder:
                        ScenarioText = "This sample is the same as InsertInSameLocation, except the items are added in normal order by increasing the MergeIndex of \"two merged items\" to be 3, \"three merged items\" to be 5, and so on.\r\n  You could also add the original items backwards to the source ContextMenuStrip.";
                        ShowInsertInSameLocationPreservingOrderSample();
                        break;
                    case MergeSample.ReplacingItems:
                        ScenarioText = "This sample replaces a menu item using MergeAction.Replace. Use this for the MDI scenario where saving does something completely different.\r\n\r\nMatching is based on the Text property. If there is no text match, merging reverts to MergeIndex.";
                        ShowReplaceSample();
                        break;
                    case MergeSample.MatchOnly:
                        ScenarioText = "This sample adds only the subitems from the child to the target ContextMenuStrip.";
                        ShowMatchOnlySample();
                        break;
                }
                // Reapply with the new settings.
                ToolStripManager.Merge(cmsItemsToMerge, cmsBase);
            }
        }
    }
    #endregion

    #region MergeSample.Append
    /* Example 1 - Add all items to the end of the list.
        * one
        * two
        * three
        * four
        * merge-one
        * merge-two
        * merge-three
        * merge-four
         */
    public void ShowAppendSample()
    {
        foreach (ToolStripItem item in cmsItemsToMerge.Items)
        {
            item.MergeAction = MergeAction.Append;
        }
    }
    #endregion

    #region MergeSample.InsertInSameLocation
    /*  Example 2 - Place all in the same location.
          * one
          * two
          * merge-four
          * merge-three
          * merge-two
          * merge-one
          * three
          * four
           
          */
    public void ShowInsertInSameLocationSample()
    {
        // Notice how the items are in backward order.  
        // This is because "merge-one" gets applied, then a search occurs for the new second position 
        // for "merge-two", and so on.
        foreach (ToolStripItem item in cmsItemsToMerge.Items)
        {
            item.MergeAction = MergeAction.Insert;
            item.MergeIndex = 2;
        }
    }
    #endregion

    #region MergeSample.InsertInSameLocationPreservingOrder
    /* Example 3 - Insert items in the right order.
        * one
        * two
        * merge-one
        * merge-two
        * merge-three
        * merge-four
        * three
        * four               
        */
    public void ShowInsertInSameLocationPreservingOrderSample()
    {

        // Undo previous merges, if any.
        ToolStripManager.RevertMerge(cmsBase, cmsItemsToMerge);

        // This is the same as above, but increases the MergeIndex so that
        // subsequent items are placed afterwards.
        int i = 0;
        foreach (ToolStripItem item in cmsItemsToMerge.Items)
        {
            item.MergeAction = MergeAction.Insert;
            item.MergeIndex = 2 + i++;
        }

        // Reapply with new settings.
        ToolStripManager.Merge(cmsItemsToMerge, cmsBase);
    }
    #endregion

    #region MergeSample.ReplacingItems
    /* Example 4 - 
        * merge-one
        * merge-two
        * merge-three
        * merge-four
         */
    public void ShowReplaceSample()
    {

        // MergeAction.Replace compares Text property values. 
        // If matching text is not found, Replace reverts to MergeIndex.                    

        foreach (ToolStripItem item in cmsItemsToMerge.Items)
        {
            item.MergeAction = MergeAction.Replace;
        }
    }
    #endregion

    #region MergeSample.MatchOnly
    /* Example 5 - Match to add subitems to a menu item.
         * Add items to the flyout menus for the original collection.
         * one -> subitem from "one merged item"
         * two -> subitem from "two merged items"
         * three -> subitem from "three merged items"
         * four -> subitem from "four merged items"
         */
    public void ShowMatchOnlySample()
    {

        foreach (ToolStripMenuItem item in cmsItemsToMerge.Items)
        {
            item.MergeAction = MergeAction.MatchOnly;
            item.DropDownItems.Add("subitem from \"" + item.Text + " " + item.ShortcutKeyDisplayString + "\"");
        }
    }
    #endregion

    private System.ComponentModel.IContainer components = null;
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.Text = "Form1";
    }
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms

Public Enum MergeSample
   None
   Append
   InsertInSameLocation
   InsertInSameLocationPreservingOrder
   ReplacingItems
   MatchOnly
End Enum

Public Class Form1
   Inherits Form
   Private cmsBase As ContextMenuStrip
   Private cmsItemsToMerge As ContextMenuStrip
   
   
   Public Sub New()
      InitializeComponent()
      
      If components Is Nothing Then
         components = New Container()
      End If
      cmsBase = New ContextMenuStrip(components)
      cmsItemsToMerge = New ContextMenuStrip(components)
      
      ' cmsBase is the base ContextMenuStrip.
      cmsBase.Items.Add("one")
      cmsBase.Items.Add("two")
      cmsBase.Items.Add("three")
      cmsBase.Items.Add("four")
      
      
      ' cmsItemsToMerge contains the items to merge.
      cmsItemsToMerge.Items.Add("one")
      cmsItemsToMerge.Items.Add("two")
      cmsItemsToMerge.Items.Add("three")
      cmsItemsToMerge.Items.Add("four")
      
      ' Distinguish the merged items by setting the shortcut display string.
      Dim tsmi As ToolStripMenuItem
      For Each tsmi In  cmsItemsToMerge.Items
         tsmi.ShortcutKeyDisplayString = "Merged Item"
      Next tsmi
      ' Associate the ContextMenuStrip with the form so that it displays when
      ' the user clicks the right mouse button.
      Me.ContextMenuStrip = cmsBase
      
      CreateCombo()
   End Sub
   
   
   #Region "ComboBox switching code."
   
   Private Sub CreateCombo()
      ' This ComboBox allows the user to switch between the samples.
      Dim sampleSelectorCombo As New ComboBox()
      sampleSelectorCombo.DataSource = [Enum].GetValues(GetType(MergeSample))
      AddHandler sampleSelectorCombo.SelectedIndexChanged, AddressOf comboBox_SelectedIndexChanged
      sampleSelectorCombo.Dock = DockStyle.Top
      Me.Controls.Add(sampleSelectorCombo)
      Dim textBox As New TextBox()
      textBox.Multiline = True
      textBox.Dock = DockStyle.Left
      textBox.DataBindings.Add("Text", Me, "ScenarioText")
      textBox.ReadOnly = True
      textBox.Width = 150
      Me.Controls.Add(textBox)
      Me.BackColor = ProfessionalColors.MenuStripGradientBegin
      Me.Text = "Right click under selection."
   End Sub
   
   Private Sub comboBox_SelectedIndexChanged(sender As Object, e As EventArgs)
      Dim sampleSelectorCombo As ComboBox = sender 
      If Not (sampleSelectorCombo.SelectedValue Is Nothing) Then
         CurrentSample = CType(sampleSelectorCombo.SelectedValue, MergeSample)
      End If
   End Sub
   
   Private scenarioText1 As String
   
   
   Public Property ScenarioText() As String
      Get
         Return scenarioText1
      End Get
      Set
         scenarioText1 = value
         RaiseEvent ScenarioTextChanged(Me, EventArgs.Empty)
      End Set
   End Property
   
   Public Event ScenarioTextChanged As EventHandler
   
   #End Region
   
   
   Private Sub RebuildItemsToMerge()
      ' This handles cases where the items collection changes for the sample.
      cmsItemsToMerge.SuspendLayout()
      cmsItemsToMerge.Items.Clear()
      cmsItemsToMerge.Items.Add("one")
      cmsItemsToMerge.Items.Add("two")
      cmsItemsToMerge.Items.Add("three")
      cmsItemsToMerge.Items.Add("four")
      ' Distinguish the merged items by setting the shortcut display string.
      Dim tsmi As ToolStripMenuItem
      For Each tsmi In  cmsItemsToMerge.Items
         tsmi.ShortcutKeyDisplayString = "Merged Item"
      Next tsmi
      cmsItemsToMerge.ResumeLayout()
   End Sub
   #Region "Switching current samples."
   Private currentSample1 As MergeSample = MergeSample.None
   
   Private Property CurrentSample() As MergeSample
      Get
         Return currentSample1
      End Get
      Set
         If currentSample1 <> value Then
            Dim resetRequired As Boolean = False
            
            If currentSample1 = MergeSample.MatchOnly Then
               resetRequired = True
            End If
            currentSample1 = value
            ' Undo previous merge, if any.
            ToolStripManager.RevertMerge(cmsBase, cmsItemsToMerge)
            If resetRequired Then
               RebuildItemsToMerge()
            End If
            
            Select Case currentSample1
               Case MergeSample.None
                     Return
               Case MergeSample.Append
                  ScenarioText = "This sample adds items to the end of the list using MergeAction.Append." + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf + "This is the default setting for MergeAction. A typical scenario is adding menu items to the end of the menu when some part of the program is activated."
                  ShowAppendSample()
               Case MergeSample.InsertInSameLocation
                  ScenarioText = "This sample adds items to the middle of the list using MergeAction.Insert." + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf + "Notice here how the items are added in reverse order: four, three, two, one. This is because they all have the same merge index." + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf + "A typical scenario is adding menu items to the middle or beginning of the menu when some part of the program is activated. "
                  ShowInsertInSameLocationSample()
               Case MergeSample.InsertInSameLocationPreservingOrder
                  ScenarioText = "This sample is the same as InsertInSameLocation, except the items are added in normal order by increasing the MergeIndex of ""two merged items"" to be 3, ""three merged items"" to be 5, and so on." + ControlChars.Cr + ControlChars.Lf + "  You could also add the original items backwards to the source ContextMenuStrip."
                  ShowInsertInSameLocationPreservingOrderSample()
               Case MergeSample.ReplacingItems
                  ScenarioText = "This sample replaces a menu item using MergeAction.Replace. Use this for the MDI scenario where saving does something completely different." + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf + "Matching is based on the Text property. If there is no text match, merging reverts to MergeIndex."
                  ShowReplaceSample()
               Case MergeSample.MatchOnly
                  ScenarioText = "This sample adds only the subitems from the child to the target ContextMenuStrip."
                  ShowMatchOnlySample()
            End Select
            
            ' Reapply with the new settings.
            ToolStripManager.Merge(cmsItemsToMerge, cmsBase)
         End If
      End Set
   End Property
   #End Region
   
   #Region "MergeSample.Append"
   
   ' Example 1 - Add all items to the end of the list.
'        * one
'        * two
'        * three
'        * four
'        * merge-one
'        * merge-two
'        * merge-three
'        * merge-four
'         
   Public Sub ShowAppendSample()
      Dim item As ToolStripItem
      For Each item In  cmsItemsToMerge.Items
         item.MergeAction = MergeAction.Append
      Next item
   End Sub
   #End Region
   
   #Region "MergeSample.InsertInSameLocation"
   
   '  Example 2 - Place all in the same location.
'          * one
'          * two
'          * merge-four
'          * merge-three
'          * merge-two
'          * merge-one
'          * three
'          * four
'           
'          
   Public Sub ShowInsertInSameLocationSample()
      ' Notice how the items are in backward order.  
      ' This is because "merge-one" gets applied, then a search occurs for the new second position 
      ' for "merge-two", and so on.
      Dim item As ToolStripItem
      For Each item In  cmsItemsToMerge.Items
         item.MergeAction = MergeAction.Insert
         item.MergeIndex = 2
      Next item
   End Sub
   #End Region
   
   #Region "MergeSample.InsertInSameLocationPreservingOrder"
   
   ' Example 3 - Insert items in the right order.
'        * one
'        * two
'        * merge-one
'        * merge-two
'        * merge-three
'        * merge-four
'        * three
'        * four               
'        
   Public Sub ShowInsertInSameLocationPreservingOrderSample()
      
      ' Undo previous merges, if any.
      ToolStripManager.RevertMerge(cmsBase, cmsItemsToMerge)
      
      ' This is the same as above, but increases the MergeIndex so that
      ' subsequent items are placed afterwards.
      Dim i As Integer = 0
      Dim item As ToolStripItem
      For Each item In  cmsItemsToMerge.Items
         item.MergeAction = MergeAction.Insert
         item.MergeIndex = 2 + i
      Next item
      
      ' Reapply with new settings.
      ToolStripManager.Merge(cmsItemsToMerge, cmsBase)
   End Sub
   #End Region
   
   #Region "MergeSample.ReplacingItems"
   
   ' Example 4 - 
'        * merge-one
'        * merge-two
'        * merge-three
'        * merge-four
'         
   Public Sub ShowReplaceSample()
      
      ' MergeAction.Replace compares Text property values. 
      ' If matching text is not found, Replace reverts to MergeIndex.                    
      Dim item As ToolStripItem
      For Each item In  cmsItemsToMerge.Items
         item.MergeAction = MergeAction.Replace
      Next item
   End Sub
   
   
   #End Region
   
   #Region "MergeSample.MatchOnly"
   
   ' Example 5 - Match to add subitems to a menu item.
'         * Add items to the flyout menus for the original collection.
'         * one -> subitem from "one merged item"
'         * two -> subitem from "two merged items"
'         * three -> subitem from "three merged items"
'         * four -> subitem from "four merged items"
'         
   Public Sub ShowMatchOnlySample()
      
      Dim item As ToolStripMenuItem
      For Each item In  cmsItemsToMerge.Items
         item.MergeAction = MergeAction.MatchOnly
         item.DropDownItems.Add(("subitem from """ + item.Text + " " + item.ShortcutKeyDisplayString + """"))
      Next item
   End Sub
   
   #End Region
   
   Private components As System.ComponentModel.IContainer = Nothing
   
   Protected Overrides Sub Dispose(disposing As Boolean)
      If disposing AndAlso Not (components Is Nothing) Then
         components.Dispose()
      End If
      MyBase.Dispose(disposing)
   End Sub
   
   
   Private Sub InitializeComponent()
      Me.components = New System.ComponentModel.Container()
      Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
      Me.Text = "Form1"
   End Sub
   
   <STAThread()>  _
   Shared Sub Main()
      Application.EnableVisualStyles()
      Application.SetCompatibleTextRenderingDefault(False)
      Application.Run(New Form1())
   End Sub
End Class

다음 코드 예제에 대 한 호출을 보여 줍니다. ToolStripManager 및 해당 멤버의 일부입니다.

toolStrip1->RenderMode = 
    ToolStripRenderMode::ManagerRenderMode;
ToolStripManager::Renderer = gcnew RedTextRenderer;
toolStrip1.RenderMode = ToolStripRenderMode.ManagerRenderMode;
ToolStripManager.Renderer = new RedTextRenderer();
toolStrip1.RenderMode = ToolStripRenderMode.ManagerRenderMode
ToolStripManager.Renderer = New RedTextRenderer()

설명

ToolStripManager 지원 ToolStrip-관련 병합, 설정 및 렌더러 옵션 등의 전체 애플리케이션에 대 한 작업입니다. 오버 로드 된 Merge 메서드 결합 ToolStrip 서로 및 오버 로드 된 컨트롤과 RevertMerge 메서드 실행 병합 작업을 취소 합니다.

사용 하 여는 ToolStripRenderer 클래스는 ToolStripManager 클래스 그리기 및 레이아웃 스타일을 통해 더 많은 컨트롤을 사용자 지정 가능성을 얻으려고 합니다.

속성

Renderer

폼의 기본 그리기 스타일을 가져오거나 설정합니다.

RenderMode

폼의 기본 테마를 가져오거나 설정합니다.

VisualStylesEnabled

ToolStrip이 테마라는 비주얼 스타일 정보를 사용하여 렌더링되는지 여부를 나타내는 값을 가져오거나 설정합니다.

메서드

FindToolStrip(String)

지정된 ToolStrip 또는 ToolStrip에서 파생된 형식을 찾습니다.

IsShortcutDefined(Keys)

폼의 ToolStrip 컨트롤에서 지정된 바로 가기 키를 사용하는지 여부를 나타내는 값을 검색합니다.

IsValidShortcut(Keys)

정의된 바로 가기 키가 유효한지를 나타내는 값을 검색합니다.

LoadSettings(Form)

Form의 전체 이름을 설정 키로 사용하여 지정된 Form에 대한 설정을 로드합니다.

LoadSettings(Form, String)

지정된 설정 키를 사용하여 지정된 Form에 대한 설정을 로드합니다.

Merge(ToolStrip, String)

같은 형식의 두 ToolStrip 개체를 결합합니다.

Merge(ToolStrip, ToolStrip)

다른 형식의 두 ToolStrip 개체를 결합합니다.

RevertMerge(String)

ToolStrip 개체의 병합을 실행 취소합니다. 지정된 이름의 ToolStrip을 병합 이전의 상태로 되돌리고 이전의 병합 작업을 모두 취소합니다.

RevertMerge(ToolStrip)

ToolStrip 개체의 병합을 실행 취소합니다. 지정된 ToolStrip을 병합 이전의 상태로 되돌리고 이전의 병합 작업을 모두 취소합니다.

RevertMerge(ToolStrip, ToolStrip)

ToolStrip 개체의 병합을 실행 취소합니다. 두 ToolStrip 컨트롤을 모두 병합 이전의 상태로 되돌리고 이전의 병합 작업을 모두 취소합니다.

SaveSettings(Form)

Form의 전체 이름을 설정 키로 사용하여 지정된 Form에 대한 설정을 저장합니다.

SaveSettings(Form, String)

지정된 설정 키를 사용하여 지정된 Form에 대한 설정을 저장합니다.

이벤트

RendererChanged

Renderer 속성 값이 변경되면 발생합니다.

적용 대상

추가 정보