You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.6 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows.Forms;
  4. namespace Apewer.WinForm
  5. {
  6. /// <summary>Windows 窗体工具。</summary>
  7. public static class Extensions
  8. {
  9. static void MenuItemEventHandler(object sender, EventArgs e)
  10. {
  11. #if NETFRAMEWORK
  12. var mi = sender as System.Windows.Forms.MenuItem;
  13. if (mi != null)
  14. {
  15. var tag = mi.Tag as MenuItem;
  16. if (tag != null && tag.Action != null) tag.Action.Invoke(tag);
  17. }
  18. #endif
  19. var tsmi = sender as System.Windows.Forms.ToolStripMenuItem;
  20. if (tsmi != null)
  21. {
  22. var tag = tsmi.Tag as MenuItem;
  23. if (tag != null && tag.Action != null) tag.Action.Invoke(tag);
  24. }
  25. }
  26. #if NETFRAMEWORK
  27. /// <summary>生成 <see cref="System.Windows.Forms.ContextMenu" /> 实例。</summary>
  28. /// <exception cref="ArgumentNullException"></exception>
  29. public static ContextMenu ContextMenu(this IEnumerable<MenuItem> items)
  30. {
  31. if (items == null) throw new ArgumentNullException(nameof(items));
  32. var cm = new ContextMenu();
  33. foreach (var item in items)
  34. {
  35. var isLine = item == null || item.Text == null || item.Text == "" || item.Text == "-";
  36. var text = isLine ? "-" : item?.Text;
  37. var mi = new System.Windows.Forms.MenuItem(text, MenuItemEventHandler);
  38. mi.Enabled = !isLine && item.Action != null;
  39. mi.Tag = item;
  40. cm.MenuItems.Add(mi);
  41. }
  42. return cm;
  43. }
  44. #endif
  45. /// <summary>生成 <see cref="ContextMenuStrip" /> 实例。</summary>
  46. /// <exception cref="ArgumentNullException"></exception>
  47. public static ContextMenuStrip ContextMenuStrip(this IEnumerable<MenuItem> items)
  48. {
  49. if (items == null) throw new ArgumentNullException(nameof(items));
  50. var cms = new ContextMenuStrip();
  51. foreach (var item in items)
  52. {
  53. if (item == null) continue;
  54. var isLine = item.Text == null || item.Text == "" || item.Text == "-";
  55. var text = isLine ? "-" : item.Text;
  56. var tsmi = new ToolStripMenuItem(text, null, MenuItemEventHandler);
  57. tsmi.AutoSize = true;
  58. tsmi.Height = isLine ? 19 : 30;
  59. tsmi.Enabled = item.Action != null && item.Action != null;
  60. tsmi.Tag = item;
  61. cms.Items.Add(tsmi);
  62. }
  63. return cms;
  64. }
  65. }
  66. }