myColorComboBox.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.ComponentModel;
  3. using System.Drawing;
  4. using System.Windows.Forms;
  5. namespace OTSIncAReportApp
  6. {
  7. /// <summary>
  8. /// 自定义颜色对话框窗体
  9. /// </summary>
  10. public partial class myColorComboBox : ComboBox
  11. {
  12. #region 构造函数
  13. public myColorComboBox()
  14. {
  15. InitializeComponent();
  16. InitItems();
  17. }
  18. public myColorComboBox(IContainer container)
  19. {
  20. container.Add(this);
  21. InitializeComponent();
  22. InitItems();
  23. }
  24. #endregion
  25. #region 初始化项
  26. private void InitItems()
  27. {
  28. this.DrawMode = DrawMode.OwnerDrawFixed;//手动绘制所有元素
  29. this.DropDownStyle = ComboBoxStyle.DropDownList;//下拉框样式设置为不能编辑
  30. this.Items.Clear();//清空原有项
  31. Array allColors = Enum.GetValues(typeof(KnownColor));//获取系统颜色名存入列表
  32. foreach (KnownColor var in allColors)
  33. {
  34. this.Items.Add(var.ToString()); //加载该选项框的子项
  35. }
  36. this.SelectedIndex = 0;
  37. }
  38. #endregion
  39. #region 绘制方法
  40. protected override void OnDrawItem(DrawItemEventArgs e)
  41. {
  42. if (e.Index >= 0)//判断是否需要重绘
  43. {
  44. string colorName = this.Items[e.Index].ToString();//获取颜色名
  45. SolidBrush brush = new SolidBrush(Color.FromName(colorName));//定义画刷
  46. Font font = new Font("宋体", 9);//定义字体
  47. Rectangle rect = e.Bounds;
  48. rect.Inflate(-2, -2);
  49. Rectangle rectColor = new Rectangle(rect.Location, new Size(20, rect.Height));
  50. e.Graphics.FillRectangle(brush, rectColor);//填充颜色
  51. e.Graphics.DrawRectangle(Pens.Black, rectColor);//绘制边框
  52. e.Graphics.DrawString(colorName, font, Brushes.Black, (rect.X + 22), rect.Y);//绘制文字
  53. }
  54. }
  55. #endregion
  56. #region 自定义控件相关属性
  57. /// <summary>
  58. /// 选择的颜色名称
  59. /// </summary>
  60. public string SelectColorName
  61. {
  62. get { return this.Text; }
  63. }
  64. /// <summary>
  65. /// 选择的颜色
  66. /// </summary>
  67. public Color SelectColor
  68. {
  69. get { return Color.FromName(this.Text); }
  70. }
  71. #endregion
  72. }
  73. }