ToastForm.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //############################################################
  2. // https://github.com/yuzhengyang
  3. // author:yuzhengyang
  4. //############################################################
  5. using System;
  6. using System.Windows.Forms;
  7. namespace Y.Skin.YoForm.Toast
  8. {
  9. public partial class ToastForm : Form
  10. {
  11. #region How to use?
  12. //ToastForm _ToastForm = null;
  13. //public void Toast(string s = "")
  14. //{
  15. // if (_ToastForm == null || _ToastForm.IsDisposed)
  16. // _ToastForm = new ToastForm(this);
  17. // _ToastForm.Toast(s);
  18. //}
  19. #endregion
  20. Form BaseForm;
  21. DateTime HideTime = DateTime.Now;
  22. int Showtime = 5;
  23. public ToastForm(Form form)
  24. {
  25. InitializeComponent();
  26. BaseForm = form;
  27. }
  28. private void ToastForm_Load(object sender, EventArgs e)
  29. {
  30. TopMost = true;
  31. ShowInTaskbar = false;
  32. }
  33. private void SetPosition()
  34. {
  35. Top = BaseForm.Top + (BaseForm.Height / 2) - (Height / 2);
  36. Left = BaseForm.Left + (BaseForm.Width / 2) - (Width / 2);
  37. }
  38. public void Toast()
  39. {
  40. BaseForm.BeginInvoke(new Action(() =>
  41. {
  42. Show();
  43. HideTime = DateTime.Now.AddSeconds(Showtime);
  44. SetPosition();
  45. TmActor.Interval = 1000;
  46. TmActor.Enabled = true;
  47. }));
  48. }
  49. public void Toast(string s)
  50. {
  51. BaseForm.BeginInvoke(new Action(() =>
  52. {
  53. LbMsg.Text = s;
  54. Show();
  55. HideTime = DateTime.Now.AddSeconds(Showtime);
  56. SetPosition();
  57. TmActor.Interval = 1000;
  58. TmActor.Enabled = true;
  59. }));
  60. }
  61. private void TmActor_Tick(object sender, EventArgs e)
  62. {
  63. if (DateTime.Now > HideTime)
  64. {
  65. Hide();
  66. TmActor.Enabled = false;
  67. }
  68. }
  69. }
  70. }