TopWindow.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8. namespace Bird_tool
  9. {
  10. public static class TopMostMessageBox
  11. {
  12. public static void Show(string message)
  13. {
  14. // 确保在UI线程执行
  15. if (Application.OpenForms.Count > 0)
  16. {
  17. Form mainForm = Application.OpenForms[0];
  18. if (mainForm.InvokeRequired)
  19. {
  20. mainForm.Invoke(new Action(() => CreateMessageBox(message)));
  21. }
  22. else
  23. {
  24. CreateMessageBox(message);
  25. }
  26. }
  27. else
  28. {
  29. // 如果没有主窗体,直接创建
  30. CreateMessageBox(message);
  31. }
  32. }
  33. private static void CreateMessageBox(string message)
  34. {
  35. using (var form = new Form
  36. {
  37. Width = 350,
  38. Height = 180,
  39. FormBorderStyle = FormBorderStyle.FixedDialog,
  40. MaximizeBox = false,
  41. MinimizeBox = false,
  42. StartPosition = FormStartPosition.CenterScreen,
  43. Text = "系统提示",
  44. TopMost = true,
  45. BackColor = System.Drawing.Color.WhiteSmoke,
  46. Padding = new Padding(10),
  47. Font = new System.Drawing.Font("微软雅黑", 10)
  48. })
  49. {
  50. // 消息标签 - 带自动换行
  51. var label = new Label
  52. {
  53. Text = message,
  54. Dock = DockStyle.Fill,
  55. TextAlign = System.Drawing.ContentAlignment.MiddleCenter,
  56. AutoSize = false,
  57. Padding = new Padding(0, 10, 0, 20)
  58. };
  59. // 确定按钮
  60. var panel = new Panel
  61. {
  62. Dock = DockStyle.Bottom,
  63. Height = 50,
  64. BackColor = Color.Transparent
  65. };
  66. // 确定按钮
  67. var button = new Button
  68. {
  69. Text = "确定",
  70. Size = new Size(80, 35),
  71. Location = new Point((panel.Width - 80) / 2, 5)
  72. };
  73. button.Click += (s, e) => form.Close();
  74. // 添加控件
  75. panel.Controls.Add(button);
  76. form.Controls.Add(label);
  77. form.Controls.Add(panel);
  78. // 为主窗体添加激活事件处理程序
  79. foreach (Form mainForm in Application.OpenForms)
  80. {
  81. if (mainForm != form)
  82. {
  83. // 安全添加事件处理
  84. mainForm.Activated += (s, e) =>
  85. {
  86. if (!form.IsDisposed)
  87. {
  88. form.TopMost = true;
  89. }
  90. };
  91. }
  92. }
  93. form.AcceptButton = button;
  94. form.ShowDialog();
  95. }
  96. }
  97. }
  98. }