123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- using BeatLyrics.Tool.Properties;
- using System;
- using System.Drawing;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace BeatLyrics.Tool.Utils
- {
- public static class LoadingWrap
- {
- private static readonly Image LoadingImage = Resources.loading;
- public static IDisposable ShowLoading(this Form control, string text, int delayMs = 500, int fadingMs = 500)
- {
- if (false == control.InvokeRequired)
- throw new InvalidOperationException("需要从非界面线程调用此方法");
- Form form = null;
- void CreateControl()
- {
- form = new Form
- {
- FormBorderStyle = FormBorderStyle.None
- ,
- Width = 320
- ,
- Height = 64
- ,
- StartPosition = FormStartPosition.CenterParent
- ,
- ShowInTaskbar = false
- ,
- Opacity = 0
- };
- var panel = new Panel { BorderStyle = BorderStyle.FixedSingle, Dock = DockStyle.Fill, };
- form.Controls.Add(panel);
- var size = Math.Min(form.Width, form.Height);
- panel.Controls.Add(new Label
- {
- Text = text,
- Dock = DockStyle.Fill,
- TextAlign = ContentAlignment.MiddleLeft,
- });
- panel.Controls.Add(new PictureBox
- {
- Dock = DockStyle.Left
- ,
- Height = size
- ,
- Width = size
- ,
- SizeMode = PictureBoxSizeMode.Zoom
- ,
- Image = LoadingImage
- });
- panel.Controls.Add(new Panel { Height = 20, Dock = DockStyle.Top });
- panel.Controls.Add(new Panel { Height = 20, Dock = DockStyle.Bottom });
- }
- const int stepMs = 100;
- var closed = false;
- var step = 1d / ((double)fadingMs / stepMs);
- void ShowInvisibleForm()
- {
- control.Invoke(new Action(() => form.ShowDialog(control)));
- }
- void DelayAndFadeIn()
- {
- Thread.Sleep(delayMs);
- if (closed)
- return;
- var alpha = 0d;
- while (false == closed && alpha < 1)
- {
- alpha += step;
- if (alpha > 1)
- alpha = 1;
- var localVar = alpha;
- control.Invoke(new Action(() => form.Opacity = localVar));
- Thread.Sleep(stepMs);
- }
- }
- void FadeOutAndClose()
- {
- closed = true;
- var alpha = 0d;
- control.Invoke(new Action(() => alpha = form.Opacity));
- while (alpha > 0)
- {
- alpha -= step;
- if (alpha < 0)
- alpha = 0;
- control.Invoke(new Action(() => form.Opacity = alpha));
- Thread.Sleep(stepMs);
- }
- control.Invoke(new Action(() => form.Close()));
- }
- control.Invoke(new Action(CreateControl));
- Task.Factory.StartNew(ShowInvisibleForm);
- Task.Factory.StartNew(DelayAndFadeIn);
- return new Disposable(FadeOutAndClose);
- }
- private class Disposable : IDisposable
- {
- private readonly Action _action;
- public Disposable(Action action)
- {
- _action = action;
- }
- public void Dispose()
- {
- _action();
- }
- }
- }
- }
|