using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows;
namespace SlnMesnac.WPF.MessageTips
{
public static class Msg
{
private static MessageAdorner messageAdorner;
///
/// 消息弹出
///
/// 消息内容
/// 消息类型;0正常,1警告,2错误
/// 自动关闭时间。默认5秒
///
public static void MsgShow(string message, int msgtype, int outTime = 3)
{
try
{
Application.Current.Dispatcher.Invoke(() =>
{
if (messageAdorner != null && messageAdorner.IsLoaded)
{
messageAdorner.PushMessage(message, msgtype, outTime);
return;
}
Window win = null;
if (Application.Current.Windows.Count > 0)
{
win = Application.Current.Windows.OfType().FirstOrDefault(o => o.IsActive);
if (win == null)
win = Application.Current.Windows.OfType().First(o => o.IsActive);
}
var layer = GetAdornerLayer(win);
if (layer == null)
throw new Exception("not AdornerLayer is null");
messageAdorner = new MessageAdorner(layer);
layer.Add(messageAdorner);
messageAdorner.PushMessage(message, msgtype, outTime);
});
}catch(Exception ex)
{
Console.WriteLine("MsgShow异常:"+ex.Message);
}
}
static AdornerLayer GetAdornerLayer(Visual visual)
{
var decorator = visual as AdornerDecorator;
if (decorator != null)
return decorator.AdornerLayer;
var presenter = visual as ScrollContentPresenter;
if (presenter != null)
return presenter.AdornerLayer;
var visualContent = (visual as Window)?.Content as Visual;
return AdornerLayer.GetAdornerLayer(visualContent ?? visual);
}
}
}