Click here to Skip to main content
15,886,078 members
Articles / Programming Languages / C#

Command Switchboard for Windows Forms

Rate me:
Please Sign up or sign in to vote.
4.83/5 (16 votes)
12 Jul 2007CPOL8 min read 73.2K   1.4K   93  
Switchboard component for user interface commands with design time support
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;

namespace SundbySoft.Controls
{
    /// <summary>
    /// Provides support for Menu based menus, ToolBar based toolbars and ContextMenu based context menus.
    /// </summary>
    /// <remarks>
    /// The following items is supported:
    /// <list type="">
    /// <item>MenuItem</item>
    /// <item>ToolBarButton</item>
    /// <item>ContextMenu</item>
    /// </list>
    /// </remarks>
    public class MenuToolBarUIItemAdapter : IUIItemAdapter
    {
        private UISwitchboard switchboard;
        private Control cachedOwnerControl;

        /// <summary>
        /// Initializes a new instance of the <see ref="MenuToolBarUIItemAdapter"/> class.
        /// Hidden to prevent construction without a switchboard.
        /// </summary>
        private MenuToolBarUIItemAdapter()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see ref="MenuToolBarUIItemAdapter"/> class with the associated command switchboard.
        /// </summary>
        /// <param name="UISwitchboard">The associated command switchboard.</param>
        public MenuToolBarUIItemAdapter(UISwitchboard UISwitchboard)
        {
            switchboard = UISwitchboard;
        }

        /// <summary>
        /// Gets the command switchboard parent for this adapter.
        /// </summary>
        /// <value>The element's switchboard owner.</value>
        public UISwitchboard UISwitchboard
        {
            get
            {
                return switchboard;
            }
        }

        /// <summary>
        /// Called when an item is added to the <see cref="UIItemCollection"/> collection.
        /// </summary>
        /// <remarks>
        /// The adapter should normally add an event handler to the Click event of this item.
        /// </remarks>
        /// <param name="applicationCommand">The command that has an item added.</param>
        /// <param name="item">The item that has been added.</param>
        public virtual void UIItemAdded(ApplicationCommand applicationCommand, object item)
        {
            MenuItem menuItem = item as MenuItem;
            if (menuItem != null)
            {
                menuItem.Click += new EventHandler(menuItem_Click);
                return;
            }

            ToolBarButton toolBarButtonItem = item as ToolBarButton;
            if (toolBarButtonItem != null)
            {
                toolBarButtonItem.Parent.ButtonClick -= new ToolBarButtonClickEventHandler(Parent_ButtonClick);
                toolBarButtonItem.Parent.ButtonClick += new ToolBarButtonClickEventHandler(Parent_ButtonClick);
                return;
            }
        }

        /// <summary>
        /// Called when an item is removed from the <see cref="UIItemCollection"/> collection.
        /// </summary>
        /// <param name="item">The item that has been removed.</param>
        public virtual void UIItemRemoved(object item)
        {
            MenuItem menuItem = item as MenuItem;
            if (menuItem != null)
            {
                menuItem.Click -= new EventHandler(menuItem_Click);
                return;
            }

            ToolBarButton toolBarButtonItem = item as ToolBarButton;
            if (toolBarButtonItem != null)
            {
                toolBarButtonItem.Parent.ButtonClick += new ToolBarButtonClickEventHandler(Parent_ButtonClick);
                return;
            }
        }

        /// <summary>
        /// Called when an item is clicked.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="EventArgs"/> that contains no data.</param>
        void menuItem_Click(object sender, EventArgs e)
        {
            MenuItem item = sender as MenuItem;
            ApplicationCommand applicationCommand = switchboard.GetApplicationCommandByItem(item);
            if (applicationCommand != null)
            {
                Control ownerControl = GetOwnerControl(sender);
                cachedOwnerControl = null;
                applicationCommand.Execute(ownerControl, item);
            }
        }

        /// <summary>
        /// Called when an item is clicked.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="ToolBarButtonClickEventArgs"/> that contains event data.</param>
        void Parent_ButtonClick(object sender, ToolBarButtonClickEventArgs e)
        {
            ToolBarButton item = e.Button;
            ApplicationCommand applicationCommand = switchboard.GetApplicationCommandByItem(item);
            if (applicationCommand != null)
            {
                Control ownerControl = GetOwnerControl(sender);
                cachedOwnerControl = null;
                applicationCommand.Execute(ownerControl, item);
            }
        }

        /// <summary>
        /// Called when a context menu is added to the <see cref="ContextMenuCollection"/> collection.
        /// </summary>
        /// <param name="contextMenu">The context menu that has been added.</param>
        public virtual void ContextMenuAdded(object contextMenu)
        {
            ContextMenu contextMenuObject = contextMenu as ContextMenu;
            contextMenuObject.Popup += new EventHandler(contextMenuObject_Popup);
        }

        /// <summary>
        /// Called when a context menu is removed from the <see cref="ContextMenuCollection"/> collection.
        /// </summary>
        /// <param name="contextMenu">The contyext menu that has been removed.</param>
        public virtual void ContextMenuRemoved(object contextMenu)
        {
            ContextMenu contextMenuObject = contextMenu as ContextMenu;
            contextMenuObject.Popup -= new EventHandler(contextMenuObject_Popup);
        }

        /// <summary>
        /// Called when a context menu is opening.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="EventArgs"/> that contains no data.</param>
        void contextMenuObject_Popup(object sender, EventArgs e)
        {
            ContextMenu contextMenu = sender as ContextMenu;
            cachedOwnerControl = contextMenu.SourceControl;
            foreach (MenuItem item in contextMenu.MenuItems)
            {
                UpdateItem(item);
            }
        }

        /// <summary>
        /// Updates the state of a tool strip item.
        /// </summary>
        /// <param name="item">The item to update.</param>
        void UpdateItem(MenuItem item)
        {
            ApplicationCommand applicationCommand = switchboard.GetApplicationCommandByItem(item);
            if (applicationCommand != null)
            {
                Control ownerControl = GetOwnerControl(item);
                applicationCommand.Update(ownerControl, item);

                foreach (MenuItem childItem in item.MenuItems)
                {
                    UpdateItem(childItem);
                }
            }
        }

        /// <summary>
        /// Get the owner control of the item.
        /// </summary>
        /// <param name="item">The item to get the owner control of.</param>
        /// <returns>The owner control of the item.</returns>
        public virtual Control GetOwnerControl(object item)
        {
            MenuItem menuItem = item as MenuItem;
            if (menuItem != null)
            {
                return cachedOwnerControl;
            }
            return null;
        }

        /// <summary>
        /// Enable or disable a item.
        /// </summary>
        /// <param name="item">The item to enable or disable</param>
        /// <param name="value">True if item should be enabled, else false.</param>
        public virtual void Enable(object item, bool value)
        {
            MenuItem menuItem = item as MenuItem;
            if (menuItem != null)
            {
                menuItem.Enabled = value;
                return;
            }

            ToolBarButton toolBarButtonItem = item as ToolBarButton;
            if (toolBarButtonItem != null)
            {
                toolBarButtonItem.Enabled = value;
                return;
            }
        }

        /// <summary>
        /// Show or hide a item.
        /// </summary>
        /// <param name="item">The item to show or hide</param>
        /// <param name="value">True if item should be visible, else false.</param>
        public virtual void Visible(object item, bool value)
        {
            MenuItem menuItem = item as MenuItem;
            if (menuItem != null)
            {
                menuItem.Visible = value;
                return;
            }

            ToolBarButton toolBarButtonItem = item as ToolBarButton;
            if (toolBarButtonItem != null)
            {
                toolBarButtonItem.Visible = value;
                return;
            }
        }

        /// <summary>
        /// Check or uncheck a item.
        /// </summary>
        /// <param name="item">The item to check or uncheck.</param>
        /// <param name="value">True if item should be checked, else false.</param>
        public virtual void Check(object item, bool value)
        {
            MenuItem menuItem = item as MenuItem;
            if (menuItem != null)
            {
                menuItem.Checked = value;
            }
        }

        /// <summary>
        /// Check if the adapter supports the specified item.
        /// </summary>
        /// <param name="item">The item to check if is supported.</param>
        /// <returns>true if the item is supported, else false.</returns>
        public virtual bool IsUIItemSupported(object item)
        {
            // Inheritance hierarchy of Menu and Toolbar items
            // - MenuItem
            // - ToolBarButton
            if (item != null)
            {
                // Check for known items
                string typeName = item.GetType().ToString();
                switch (typeName)
                {
                    case "System.Windows.Forms.MenuItem": return true;
                    case "System.Windows.Forms.ToolBarButton": return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Get supported items in the container.
        /// </summary>
        /// <returns>The collection of supported items.</returns>
        public virtual object[] GetAvailableUIItems()
        {
            List<object> availableItems = new List<object>();
            foreach (Component component in switchboard.Container.Components)
            {
                if (IsUIItemSupported(component))
                {
                    availableItems.Add(component);
                }
            }
            object[] itemsArray = new object[availableItems.Count];
            availableItems.CopyTo(itemsArray);
            return itemsArray;
        }

        /// <summary>
        /// Check if the adapter supports the specified context menu.
        /// </summary>
        /// <param name="contextMenu">The context menu to check if is supported.</param>
        /// <returns>true if the context menu is supported, else false.</returns>
        public virtual bool IsContextMenuSupported(object contextMenu)
        {
            if (contextMenu != null)
            {
                // Check for known items
                string typeName = contextMenu.GetType().ToString();
                switch (typeName)
                {
                    case "System.Windows.Forms.ContextMenu": return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Get supported context menus in the container.
        /// </summary>
        /// <returns>The collection of supported context menus.</returns>
        public virtual object[] GetAvailableContextMenus()
        {
            List<object> availableItems = new List<object>();
            foreach (Component component in switchboard.Container.Components)
            {
                if (IsContextMenuSupported(component))
                {
                    availableItems.Add(component);
                }
            }
            object[] itemsArray = new object[availableItems.Count];
            availableItems.CopyTo(itemsArray);
            return itemsArray;
        }

        /// <summary>
        /// Get the name of the item.
        /// </summary>
        /// <param name="item">Item to get name from</param>
        /// <returns>The item name.</returns>
        public virtual string GetUIItemName(object item)
        {
            if (item != null)
            {
                // Check for known items
                string typeName = item.GetType().ToString();
                switch (typeName)
                {
                    case "System.Windows.Forms.MenuItem":
                        MenuItem menuItem = item as MenuItem;
                        return menuItem.Name;
                    case "System.Windows.Forms.":
                        ToolBarButton toolBarButton = item as ToolBarButton;
                        return toolBarButton.Name;
                }
            }
            return null;
        }

        /// <summary>
        /// Get the name of the context menu.
        /// </summary>
        /// <param name="contextMenu">Context menu to get name from</param>
        /// <returns>The context menu name.</returns>
        public virtual string GetContextMenuName(object contextMenu)
        {
            ContextMenu item = contextMenu as ContextMenu;
            if (item != null)
            {
                return item.Name;
            }
            return null;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Sundby Software
Norway Norway
Bjørn has developed software since 1984 mainly in C, C++ and C#.

Bjørn lives in Ormåsen, Buskerud in Norway. To contact Bjørn, email him at bjsundby@online.no. He also has a web site at http://www.sundbysoft.com.

Comments and Discussions