官网

http://www.hzhcontrols.com

前提

入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章。

GitHub:https://github.com/kwwwvagaa/NetWinformControl

码云:https://gitee.com/kwwwvagaa/net_winform_custom_control.git

如果觉得写的还行,请点个 star 支持一下吧

欢迎前来交流探讨: 企鹅群568015492 

来都来了,点个【推荐】再走吧,谢谢

NuGet

Install-Package HZH_Controls

目录

https://www.cnblogs.com/bfyx/p/11364884.html

用处及效果

准备工作

主要用的就是停靠窗体了,(十九)c#Winform自定义控件-停靠窗体,不了解的可以先去看一下

思路:

通过实体对象设置的对齐方式来实现左右对齐,

当鼠标进入一项的时候,判断是否弹出下拉列表,或关闭其他列表

开始

添加一个类用来设置节点信息

   public class NavigationMenuItem
{
/// <summary>
/// The icon
/// </summary>
private Image icon;
/// <summary>
/// Gets or sets the icon.
/// </summary>
/// <value>The icon.</value>
[Description("图标,仅顶级节点有效")]
public Image Icon
{
get { return icon; }
set { icon = value; }
} /// <summary>
/// The text
/// </summary>
private string text;
/// <summary>
/// Gets or sets the text.
/// </summary>
/// <value>The text.</value> [Description("文本")]
public string Text
{
get { return text; }
set { text = value; }
} /// <summary>
/// The show tip
/// </summary>
private bool showTip;
/// <summary>
/// Gets or sets a value indicating whether [show tip].当TipText为空时只显示一个小圆点,否则显示TipText文字
/// </summary>
/// <value><c>true</c> if [show tip]; otherwise, <c>false</c>.</value>
[Description("是否显示角标,仅顶级节点有效")]
public bool ShowTip
{
get { return showTip; }
set { showTip = value; }
} /// <summary>
/// The tip text
/// </summary>
private string tipText;
/// <summary>
/// Gets or sets the tip text
/// </summary>
/// <value>The tip text.</value>
[Description("角标文字,仅顶级节点有效")]
public string TipText
{
get { return tipText; }
set { tipText = value; }
}
/// <summary>
/// The items
/// </summary>
private NavigationMenuItem[] items;
/// <summary>
/// Gets or sets the items.
/// </summary>
/// <value>The items.</value>
[Description("子项列表")]
public NavigationMenuItem[] Items
{
get { return items; }
set
{
items = value;
if (value != null)
{
foreach (var item in value)
{
item.ParentItem = this;
}
}
}
} /// <summary>
/// The anchor right
/// </summary>
private bool anchorRight; /// <summary>
/// Gets or sets a value indicating whether [anchor right].
/// </summary>
/// <value><c>true</c> if [anchor right]; otherwise, <c>false</c>.</value>
[Description("是否靠右对齐")]
public bool AnchorRight
{
get { return anchorRight; }
set { anchorRight = value; }
} /// <summary>
/// The item width
/// </summary>
private int itemWidth = ; /// <summary>
/// Gets or sets the width of the item.
/// </summary>
/// <value>The width of the item.</value>
[Description("宽度")]
public int ItemWidth
{
get { return itemWidth; }
set { itemWidth = value; }
} /// <summary>
/// Gets or sets the data source.
/// </summary>
/// <value>The data source.</value>
[Description("数据源")]
public object DataSource { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance has split lint at top.
/// </summary>
/// <value><c>true</c> if this instance has split lint at top; otherwise, <c>false</c>.</value>
[Description("是否在此项顶部显示一个分割线")]
public bool HasSplitLintAtTop { get; set; } /// <summary>
/// Gets the parent item.
/// </summary>
/// <value>The parent item.</value>
[Description("父节点")]
public NavigationMenuItem ParentItem { get; private set; }
}

添加一个自定义控件UCNavigationMenu

添加一些属性

 /// <summary>
/// Occurs when [click itemed].
/// </summary>
[Description("点击节点事件"), Category("自定义")] public event EventHandler ClickItemed;
/// <summary>
/// The select item
/// </summary>
private NavigationMenuItem selectItem = null; /// <summary>
/// Gets the select item.
/// </summary>
/// <value>The select item.</value>
[Description("选中的节点"), Category("自定义")]
public NavigationMenuItem SelectItem
{
get { return selectItem; }
private set { selectItem = value; }
} /// <summary>
/// The items
/// </summary>
NavigationMenuItem[] items; /// <summary>
/// Gets or sets the items.
/// </summary>
/// <value>The items.</value>
[Description("节点列表"), Category("自定义")]
public NavigationMenuItem[] Items
{
get { return items; }
set
{
items = value;
ReloadMenu();
}
} /// <summary>
/// The tip color
/// </summary>
private Color tipColor = Color.FromArgb(, , ); /// <summary>
/// Gets or sets the color of the tip.
/// </summary>
/// <value>The color of the tip.</value>
[Description("角标颜色"), Category("自定义")]
public Color TipColor
{
get { return tipColor; }
set { tipColor = value; }
} /// <summary>
/// 获取或设置控件的前景色。
/// </summary>
/// <value>The color of the fore.</value>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
public override System.Drawing.Color ForeColor
{
get
{
return base.ForeColor;
}
set
{
base.ForeColor = value;
foreach (Control c in this.Controls)
{
c.ForeColor = value;
}
}
}
/// <summary>
/// 获取或设置控件显示的文字的字体。
/// </summary>
/// <value>The font.</value>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" />
/// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
public override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
foreach (Control c in this.Controls)
{
c.Font = value;
}
}
} /// <summary>
/// The m LST anchors
/// </summary>
Dictionary<NavigationMenuItem, FrmAnchor> m_lstAnchors = new Dictionary<NavigationMenuItem, FrmAnchor>();

重载菜单

   private void ReloadMenu()
{
try
{
ControlHelper.FreezeControl(this, true);
this.Controls.Clear();
if (items != null && items.Length > )
{
foreach (var item in items)
{
var menu = (NavigationMenuItem)item;
Label lbl = new Label();
lbl.AutoSize = false;
lbl.TextAlign = ContentAlignment.MiddleCenter;
lbl.Width = menu.ItemWidth;
lbl.Text = menu.Text; lbl.Font = Font;
lbl.ForeColor = ForeColor; lbl.Paint += lbl_Paint;
lbl.MouseEnter += lbl_MouseEnter;
lbl.Tag = menu;
lbl.Click += lbl_Click;
if (menu.AnchorRight)
{
lbl.Dock = DockStyle.Right;
}
else
{
lbl.Dock = DockStyle.Left;
}
this.Controls.Add(lbl); lbl.BringToFront();
} }
}
finally
{
ControlHelper.FreezeControl(this, false);
}
}

显示下级菜单

 private void ShowMoreMenu(Label lbl)
{
var menu = (NavigationMenuItem)lbl.Tag;
if (CheckShow(menu))
{
if (menu.Items != null && menu.Items.Length > )
{
Panel panel = new Panel();
panel.BackColor = Color.White;
panel.Paint += panel_Paint;
panel.Padding = new System.Windows.Forms.Padding();
Size size = GetItemsSize(menu.Items);
var height = size.Height * menu.Items.Length + ;
height += menu.Items.Count(p => p.HasSplitLintAtTop);//分割线
if (size.Width < lbl.Width)
size.Width = lbl.Width;
panel.Size = new Size(size.Width, height); foreach (var item in menu.Items)
{
if (item.HasSplitLintAtTop)
{
UCSplitLine_H line = new UCSplitLine_H();
line.Dock = DockStyle.Top;
panel.Controls.Add(line);
line.BringToFront();
}
Label _lbl = new Label();
_lbl.Font = Font;
_lbl.ForeColor = this.BackColor;
_lbl.AutoSize = false;
_lbl.TextAlign = ContentAlignment.MiddleCenter;
_lbl.Height = size.Height;
_lbl.Text = item.Text;
_lbl.Dock = DockStyle.Top;
_lbl.BringToFront();
_lbl.Paint += lbl_Paint;
_lbl.MouseEnter += lbl_MouseEnter;
_lbl.Tag = item;
_lbl.Click += lbl_Click;
_lbl.Size = new System.Drawing.Size(size.Width, size.Height);
panel.Controls.Add(_lbl);
_lbl.BringToFront();
}
Point point = Point.Empty; if (menu.ParentItem != null)
{
Point p = lbl.Parent.PointToScreen(lbl.Location);
if (p.X + lbl.Width + panel.Width > Screen.PrimaryScreen.Bounds.Width)
{
point = new Point(- * panel.Width - , - * lbl.Height);
}
else
{
point = new Point(panel.Width + , - * lbl.Height);
}
}
m_lstAnchors[menu] = new FrmAnchor(lbl, panel, point);
m_lstAnchors[menu].FormClosing += UCNavigationMenu_FormClosing;
m_lstAnchors[menu].Show();
m_lstAnchors[menu].Size = new Size(size.Width, height);
}
} }

辅助函数

   /// <summary>
/// Checks the show.
/// </summary>
/// <param name="menu">The menu.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
private bool CheckShow(NavigationMenuItem menu)
{
//检查已经打开的节点
if (m_lstAnchors.ContainsKey(menu))
{
CloseList(menu);
return false;
}
if (HasInCacheChild(menu))
{
if (m_lstAnchors.ContainsKey(menu.ParentItem))
{
CloseList(menu.ParentItem);
return true;
}
return false;
}
else
{
for (int i = ; i < ; )
{
try
{
foreach (var item in m_lstAnchors)
{
if (m_lstAnchors[item.Key] != null && !m_lstAnchors[item.Key].IsDisposed)
{
m_lstAnchors[item.Key].Close();
}
}
}
catch
{
continue;
}
i++;
}
m_lstAnchors.Clear();
return true;
}
} /// <summary>
/// Determines whether [has in cache child] [the specified menu].
/// </summary>
/// <param name="menu">The menu.</param>
/// <returns><c>true</c> if [has in cache child] [the specified menu]; otherwise, <c>false</c>.</returns>
private bool HasInCacheChild(NavigationMenuItem menu)
{
foreach (var item in m_lstAnchors)
{
if (item.Key == menu)
{
return true;
}
else
{
if (item.Key.Items != null)
{
if (item.Key.Items.Contains(menu))
return true;
}
}
}
return false;
} /// <summary>
/// Closes the list.
/// </summary>
/// <param name="menu">The menu.</param>
private void CloseList(NavigationMenuItem menu)
{
if (menu.Items != null)
{
foreach (var item in menu.Items)
{
CloseList(item);
if (m_lstAnchors.ContainsKey(item))
{
if (m_lstAnchors[item] != null && !m_lstAnchors[item].IsDisposed)
{
m_lstAnchors[item].Close();
m_lstAnchors[item] = null;
m_lstAnchors.Remove(item);
}
}
}
}
}

一些事件

 /// <summary>
/// Handles the Click event of the lbl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
void lbl_Click(object sender, EventArgs e)
{
Label lbl = sender as Label;
if (lbl.Tag != null)
{
var menu = (NavigationMenuItem)lbl.Tag;
if (menu.Items == null || menu.Items.Length <= )
{
selectItem = menu; while (m_lstAnchors.Count > )
{
try
{
foreach (var item in m_lstAnchors)
{
item.Value.Close();
m_lstAnchors.Remove(item.Key);
}
}
catch { }
} if (ClickItemed != null)
{
ClickItemed(this, e);
}
}
else
{
CloseList(menu);
if (m_lstAnchors.ContainsKey(menu))
{
if (m_lstAnchors[menu] != null && !m_lstAnchors[menu].IsDisposed)
{
m_lstAnchors[menu].Close();
}
m_lstAnchors.Remove(menu);
}
ShowMoreMenu(lbl);
}
}
} /// <summary>
/// Handles the MouseEnter event of the lbl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
void lbl_MouseEnter(object sender, EventArgs e)
{
Label lbl = sender as Label;
ShowMoreMenu(lbl);
}
/// <summary>
/// Handles the FormClosing event of the UCNavigationMenu control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="FormClosingEventArgs"/> instance containing the event data.</param>
void UCNavigationMenu_FormClosing(object sender, FormClosingEventArgs e)
{
FrmAnchor frm = sender as FrmAnchor;
if (m_lstAnchors.ContainsValue(frm))
{
foreach (var item in m_lstAnchors)
{
if (item.Value == frm)
{
m_lstAnchors.Remove(item.Key);
return;
}
}
}
} /// <summary>
/// Handles the Paint event of the panel control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="PaintEventArgs"/> instance containing the event data.</param>
void panel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SetGDIHigh();
Rectangle rect = new Rectangle(, , e.ClipRectangle.Width - , e.ClipRectangle.Height - );
var path = rect.CreateRoundedRectanglePath();
e.Graphics.DrawPath(new Pen(new SolidBrush(LineColors.Light)), path);
} /// <summary>
/// Gets the size of the items.
/// </summary>
/// <param name="items">The items.</param>
/// <returns>Size.</returns>
private Size GetItemsSize(NavigationMenuItem[] items)
{
Size size = Size.Empty;
if (items != null && items.Length > )
{
using (var g = this.CreateGraphics())
{
foreach (NavigationMenuItem item in items)
{
var s = g.MeasureString(item.Text, Font);
if (s.Width + > size.Width)
{
size.Width = (int)s.Width + ;
}
if (s.Height + > size.Height)
{
size.Height = (int)s.Height + ;
}
}
}
}
return size;
} /// <summary>
/// Handles the Paint event of the lbl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="PaintEventArgs"/> instance containing the event data.</param>
void lbl_Paint(object sender, PaintEventArgs e)
{
Label lbl = sender as Label;
if (lbl.Tag != null)
{
var menu = (NavigationMenuItem)lbl.Tag;
e.Graphics.SetGDIHigh();
if (menu.ParentItem == null)//顶级节点支持图标和角标
{
if (menu.ShowTip)
{
if (!string.IsNullOrEmpty(menu.TipText))
{
var rect = new Rectangle(lbl.Width - , lbl.Height / - , , );
var path = rect.CreateRoundedRectanglePath();
e.Graphics.FillPath(new SolidBrush(tipColor), path);
e.Graphics.DrawString(menu.TipText, new Font("微软雅黑", 8f), new SolidBrush(Color.White), rect, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
}
else
{
e.Graphics.FillEllipse(new SolidBrush(tipColor), new Rectangle(lbl.Width - , lbl.Height / - , , ));
}
}
if (menu.Icon != null)
{
e.Graphics.DrawImage(menu.Icon, new Rectangle(, (lbl.Height - ) / , , ), , , menu.Icon.Width, menu.Icon.Height, GraphicsUnit.Pixel);
}
}
if (menu.ParentItem != null && menu.Items != null && menu.Items.Length > )
{
ControlHelper.PaintTriangle(e.Graphics, new SolidBrush(this.BackColor), new Point(lbl.Width - , (lbl.Height - ) / ), , GraphDirection.Rightward);
}
}
}

完整代码

 // ***********************************************************************
// Assembly : HZH_Controls
// Created : 2019-10-08
//
// ***********************************************************************
// <copyright file="UCNavigationMenu.cs">
// Copyright by Huang Zhenghui(黄正辉) All, QQ group:568015492 QQ:623128629 Email:623128629@qq.com
// </copyright>
//
// Blog: https://www.cnblogs.com/bfyx
// GitHub:https://github.com/kwwwvagaa/NetWinformControl
// gitee:https://gitee.com/kwwwvagaa/net_winform_custom_control.git
//
// If you use this code, please keep this note.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HZH_Controls.Forms; namespace HZH_Controls.Controls
{
/// <summary>
/// Class UCNavigationMenu.
/// Implements the <see cref="System.Windows.Forms.UserControl" />
/// </summary>
/// <seealso cref="System.Windows.Forms.UserControl" />
[DefaultEvent("ClickItemed")]
public partial class UCNavigationMenu : UserControl
{
/// <summary>
/// Occurs when [click itemed].
/// </summary>
[Description("点击节点事件"), Category("自定义")] public event EventHandler ClickItemed;
/// <summary>
/// The select item
/// </summary>
private NavigationMenuItem selectItem = null; /// <summary>
/// Gets the select item.
/// </summary>
/// <value>The select item.</value>
[Description("选中的节点"), Category("自定义")]
public NavigationMenuItem SelectItem
{
get { return selectItem; }
private set { selectItem = value; }
} /// <summary>
/// The items
/// </summary>
NavigationMenuItem[] items; /// <summary>
/// Gets or sets the items.
/// </summary>
/// <value>The items.</value>
[Description("节点列表"), Category("自定义")]
public NavigationMenuItem[] Items
{
get { return items; }
set
{
items = value;
ReloadMenu();
}
} /// <summary>
/// The tip color
/// </summary>
private Color tipColor = Color.FromArgb(, , ); /// <summary>
/// Gets or sets the color of the tip.
/// </summary>
/// <value>The color of the tip.</value>
[Description("角标颜色"), Category("自定义")]
public Color TipColor
{
get { return tipColor; }
set { tipColor = value; }
} /// <summary>
/// 获取或设置控件的前景色。
/// </summary>
/// <value>The color of the fore.</value>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
public override System.Drawing.Color ForeColor
{
get
{
return base.ForeColor;
}
set
{
base.ForeColor = value;
foreach (Control c in this.Controls)
{
c.ForeColor = value;
}
}
}
/// <summary>
/// 获取或设置控件显示的文字的字体。
/// </summary>
/// <value>The font.</value>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" />
/// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
public override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
foreach (Control c in this.Controls)
{
c.Font = value;
}
}
} /// <summary>
/// The m LST anchors
/// </summary>
Dictionary<NavigationMenuItem, FrmAnchor> m_lstAnchors = new Dictionary<NavigationMenuItem, FrmAnchor>(); /// <summary>
/// Initializes a new instance of the <see cref="UCNavigationMenu"/> class.
/// </summary>
public UCNavigationMenu()
{
InitializeComponent();
items = new NavigationMenuItem[];
if (ControlHelper.IsDesignMode())
{
items = new NavigationMenuItem[];
for (int i = ; i < ; i++)
{
items[i] = new NavigationMenuItem()
{
Text = "菜单" + (i + ),
AnchorRight = i >=
};
}
}
} /// <summary>
/// Reloads the menu.
/// </summary>
private void ReloadMenu()
{
try
{
ControlHelper.FreezeControl(this, true);
this.Controls.Clear();
if (items != null && items.Length > )
{
foreach (var item in items)
{
var menu = (NavigationMenuItem)item;
Label lbl = new Label();
lbl.AutoSize = false;
lbl.TextAlign = ContentAlignment.MiddleCenter;
lbl.Width = menu.ItemWidth;
lbl.Text = menu.Text; lbl.Font = Font;
lbl.ForeColor = ForeColor; lbl.Paint += lbl_Paint;
lbl.MouseEnter += lbl_MouseEnter;
lbl.Tag = menu;
lbl.Click += lbl_Click;
if (menu.AnchorRight)
{
lbl.Dock = DockStyle.Right;
}
else
{
lbl.Dock = DockStyle.Left;
}
this.Controls.Add(lbl); lbl.BringToFront();
} }
}
finally
{
ControlHelper.FreezeControl(this, false);
}
} /// <summary>
/// Handles the Click event of the lbl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
void lbl_Click(object sender, EventArgs e)
{
Label lbl = sender as Label;
if (lbl.Tag != null)
{
var menu = (NavigationMenuItem)lbl.Tag;
if (menu.Items == null || menu.Items.Length <= )
{
selectItem = menu; while (m_lstAnchors.Count > )
{
try
{
foreach (var item in m_lstAnchors)
{
item.Value.Close();
m_lstAnchors.Remove(item.Key);
}
}
catch { }
} if (ClickItemed != null)
{
ClickItemed(this, e);
}
}
else
{
CloseList(menu);
if (m_lstAnchors.ContainsKey(menu))
{
if (m_lstAnchors[menu] != null && !m_lstAnchors[menu].IsDisposed)
{
m_lstAnchors[menu].Close();
}
m_lstAnchors.Remove(menu);
}
ShowMoreMenu(lbl);
}
}
} /// <summary>
/// Handles the MouseEnter event of the lbl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
void lbl_MouseEnter(object sender, EventArgs e)
{
Label lbl = sender as Label;
ShowMoreMenu(lbl);
} /// <summary>
/// Checks the show.
/// </summary>
/// <param name="menu">The menu.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
private bool CheckShow(NavigationMenuItem menu)
{
//检查已经打开的节点
if (m_lstAnchors.ContainsKey(menu))
{
CloseList(menu);
return false;
}
if (HasInCacheChild(menu))
{
if (m_lstAnchors.ContainsKey(menu.ParentItem))
{
CloseList(menu.ParentItem);
return true;
}
return false;
}
else
{
for (int i = ; i < ; )
{
try
{
foreach (var item in m_lstAnchors)
{
if (m_lstAnchors[item.Key] != null && !m_lstAnchors[item.Key].IsDisposed)
{
m_lstAnchors[item.Key].Close();
}
}
}
catch
{
continue;
}
i++;
}
m_lstAnchors.Clear();
return true;
}
} /// <summary>
/// Determines whether [has in cache child] [the specified menu].
/// </summary>
/// <param name="menu">The menu.</param>
/// <returns><c>true</c> if [has in cache child] [the specified menu]; otherwise, <c>false</c>.</returns>
private bool HasInCacheChild(NavigationMenuItem menu)
{
foreach (var item in m_lstAnchors)
{
if (item.Key == menu)
{
return true;
}
else
{
if (item.Key.Items != null)
{
if (item.Key.Items.Contains(menu))
return true;
}
}
}
return false;
} /// <summary>
/// Closes the list.
/// </summary>
/// <param name="menu">The menu.</param>
private void CloseList(NavigationMenuItem menu)
{
if (menu.Items != null)
{
foreach (var item in menu.Items)
{
CloseList(item);
if (m_lstAnchors.ContainsKey(item))
{
if (m_lstAnchors[item] != null && !m_lstAnchors[item].IsDisposed)
{
m_lstAnchors[item].Close();
m_lstAnchors[item] = null;
m_lstAnchors.Remove(item);
}
}
}
}
} /// <summary>
/// Shows the more menu.
/// </summary>
/// <param name="lbl">The label.</param>
private void ShowMoreMenu(Label lbl)
{
var menu = (NavigationMenuItem)lbl.Tag;
if (CheckShow(menu))
{
if (menu.Items != null && menu.Items.Length > )
{
Panel panel = new Panel();
panel.BackColor = Color.White;
panel.Paint += panel_Paint;
panel.Padding = new System.Windows.Forms.Padding();
Size size = GetItemsSize(menu.Items);
var height = size.Height * menu.Items.Length + ;
height += menu.Items.Count(p => p.HasSplitLintAtTop);//分割线
if (size.Width < lbl.Width)
size.Width = lbl.Width;
panel.Size = new Size(size.Width, height); foreach (var item in menu.Items)
{
if (item.HasSplitLintAtTop)
{
UCSplitLine_H line = new UCSplitLine_H();
line.Dock = DockStyle.Top;
panel.Controls.Add(line);
line.BringToFront();
}
Label _lbl = new Label();
_lbl.Font = Font;
_lbl.ForeColor = this.BackColor;
_lbl.AutoSize = false;
_lbl.TextAlign = ContentAlignment.MiddleCenter;
_lbl.Height = size.Height;
_lbl.Text = item.Text;
_lbl.Dock = DockStyle.Top;
_lbl.BringToFront();
_lbl.Paint += lbl_Paint;
_lbl.MouseEnter += lbl_MouseEnter;
_lbl.Tag = item;
_lbl.Click += lbl_Click;
_lbl.Size = new System.Drawing.Size(size.Width, size.Height);
panel.Controls.Add(_lbl);
_lbl.BringToFront();
}
Point point = Point.Empty; if (menu.ParentItem != null)
{
Point p = lbl.Parent.PointToScreen(lbl.Location);
if (p.X + lbl.Width + panel.Width > Screen.PrimaryScreen.Bounds.Width)
{
point = new Point(- * panel.Width - , - * lbl.Height);
}
else
{
point = new Point(panel.Width + , - * lbl.Height);
}
}
m_lstAnchors[menu] = new FrmAnchor(lbl, panel, point);
m_lstAnchors[menu].FormClosing += UCNavigationMenu_FormClosing;
m_lstAnchors[menu].Show();
m_lstAnchors[menu].Size = new Size(size.Width, height);
}
} } /// <summary>
/// Handles the FormClosing event of the UCNavigationMenu control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="FormClosingEventArgs"/> instance containing the event data.</param>
void UCNavigationMenu_FormClosing(object sender, FormClosingEventArgs e)
{
FrmAnchor frm = sender as FrmAnchor;
if (m_lstAnchors.ContainsValue(frm))
{
foreach (var item in m_lstAnchors)
{
if (item.Value == frm)
{
m_lstAnchors.Remove(item.Key);
return;
}
}
}
} /// <summary>
/// Handles the Paint event of the panel control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="PaintEventArgs"/> instance containing the event data.</param>
void panel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SetGDIHigh();
Rectangle rect = new Rectangle(, , e.ClipRectangle.Width - , e.ClipRectangle.Height - );
var path = rect.CreateRoundedRectanglePath();
e.Graphics.DrawPath(new Pen(new SolidBrush(LineColors.Light)), path);
} /// <summary>
/// Gets the size of the items.
/// </summary>
/// <param name="items">The items.</param>
/// <returns>Size.</returns>
private Size GetItemsSize(NavigationMenuItem[] items)
{
Size size = Size.Empty;
if (items != null && items.Length > )
{
using (var g = this.CreateGraphics())
{
foreach (NavigationMenuItem item in items)
{
var s = g.MeasureString(item.Text, Font);
if (s.Width + > size.Width)
{
size.Width = (int)s.Width + ;
}
if (s.Height + > size.Height)
{
size.Height = (int)s.Height + ;
}
}
}
}
return size;
} /// <summary>
/// Handles the Paint event of the lbl control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="PaintEventArgs"/> instance containing the event data.</param>
void lbl_Paint(object sender, PaintEventArgs e)
{
Label lbl = sender as Label;
if (lbl.Tag != null)
{
var menu = (NavigationMenuItem)lbl.Tag;
e.Graphics.SetGDIHigh();
if (menu.ParentItem == null)//顶级节点支持图标和角标
{
if (menu.ShowTip)
{
if (!string.IsNullOrEmpty(menu.TipText))
{
var rect = new Rectangle(lbl.Width - , lbl.Height / - , , );
var path = rect.CreateRoundedRectanglePath();
e.Graphics.FillPath(new SolidBrush(tipColor), path);
e.Graphics.DrawString(menu.TipText, new Font("微软雅黑", 8f), new SolidBrush(Color.White), rect, new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
}
else
{
e.Graphics.FillEllipse(new SolidBrush(tipColor), new Rectangle(lbl.Width - , lbl.Height / - , , ));
}
}
if (menu.Icon != null)
{
e.Graphics.DrawImage(menu.Icon, new Rectangle(, (lbl.Height - ) / , , ), , , menu.Icon.Width, menu.Icon.Height, GraphicsUnit.Pixel);
}
}
if (menu.ParentItem != null && menu.Items != null && menu.Items.Length > )
{
ControlHelper.PaintTriangle(e.Graphics, new SolidBrush(this.BackColor), new Point(lbl.Width - , (lbl.Height - ) / ), , GraphDirection.Rightward);
}
}
}
}
}

最后的话

如果你喜欢的话,请到 https://gitee.com/kwwwvagaa/net_winform_custom_control 点个星星吧

(七十九)c#Winform自定义控件-导航菜单的更多相关文章

  1. (十三)c#Winform自定义控件-导航菜单

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...

  2. (八十四)c#Winform自定义控件-导航菜单(类Office菜单)

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kwwwvagaa/NetWinformControl 码云:ht ...

  3. (八十三)c#Winform自定义控件-导航菜单(扩展)

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kwwwvagaa/NetWinformControl 码云:ht ...

  4. (七十)c#Winform自定义控件-饼状图

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kwwwvagaa/NetWinformControl 码云:ht ...

  5. 第三百七十九节,Django+Xadmin打造上线标准的在线教育平台—xadmin的安装

    第三百七十九节,Django+Xadmin打造上线标准的在线教育平台—xadmin的安装 xadmin介绍 xadmin是基于Django的admin开发的更完善的后台管理系统,页面基于Bootstr ...

  6. “全栈2019”Java第七十九章:类中可以嵌套接口吗?

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  7. (三十)c#Winform自定义控件-文本框(三)

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...

  8. (七十三)c#Winform自定义控件-资源加载窗体

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kwwwvagaa/NetWinformControl 码云:ht ...

  9. (二十)c#Winform自定义控件-有后退的窗体

    前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...

随机推荐

  1. NLP(十八) 一维卷积网络IMDB情感分析

    准备 Keras的IMDB数据集,包含一个词集和对应的情感标签 import pandas as pd from keras.preprocessing import sequence from ke ...

  2. SDU暑期集训排位(9)

    SDU暑期集训排位(9) G. Just Some Permutations 基础 DP 练习部分 定义 \(f(S)\),表示让 S 中的人全 happy 的方案数. \(dp[i][j]\) 表示 ...

  3. Codeforces 1058 D. Vasya and Triangle 分解因子

    传送门:http://codeforces.com/contest/1058/problem/D 题意: 在一个n*m的格点中,问能否找到三个点,使得这三个点围成的三角形面积是矩形的1/k. 思路: ...

  4. POJ-1847 Tram( 最短路 )

    题目链接:http://poj.org/problem?id=1847 Description Tram network in Zagreb consists of a number of inter ...

  5. 天梯杯 PAT L2-001. 紧急救援 最短路变形

    作为一个城市的应急救援队伍的负责人,你有一张特殊的全国地图.在地图上显示有多个分散的城市和一些连接城市的快速道路.每个城市的救援队数量和每一条连接两个城市的快速道路长度都标在地图上.当其他城市有紧急求 ...

  6. javascript 多个异步处理解决方法

    JS异步处理真是一个让人头疼的东西,尤其是AJAX这个玩意.刚开始为了方便我会将jquery ajax 这个属性这样设置 async: false但是这样做问题很多,会让浏览器假死,好在ajax提供了 ...

  7. webstrom 内存溢出,软件崩溃卡死解决的方法

    今天用gulp搭建了一个工程,准备做一个体育h5的项目,其中需要用到sass代码压缩,加版本号等功能. gulpfile.js和package.json都是已经写好的.我用CMD命令窗口cnpm安装n ...

  8. Dijkstra算法的Java实现

    package main.java; import main.java.utils.GraphUtil; import java.util.ArrayDeque; import java.util.L ...

  9. 快速了解TCP的流量控制与拥塞控制

    有关TCP你不能不知道的三次握手和四次挥手问题,点我跳转 流量控制 1. 滑动窗口 数据的传送过程中很可能出现接收方来不及接收的情况,这时就需要对发送方进行控制以免数据丢失.利用滑动窗口机制可以很方便 ...

  10. [币严区块链]数字货币交易所之以太坊(ETH)钱包对接(四) 使用web3j对接以太坊钱包

    本文给大家介绍了 Web3j Java 版本的框架的基本使用,大家可根据本文的内容进行扩展性的练习,对其他 API 的使用进行尝试. 使用web3j对接以太坊钱包 一.开发准备事项 启动 Geth 此 ...