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

64 lines
2.3 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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;
/// <summary>
/// 消息弹出
/// </summary>
/// <param name="message">消息内容</param>
/// <param name="msgtype">消息类型;0正常1警告2错误</param>
/// <param name="outTime">自动关闭时间。默认5秒</param>
/// <exception cref="Exception"></exception>
public static void MsgShow(string message, int msgtype, int outTime = 3)
{
try
{
if (messageAdorner != null)
{
messageAdorner.PushMessage(message, msgtype, outTime);
return;
}
Window win = null;
if (Application.Current.Windows.Count > 0)
{
win = Application.Current.Windows.OfType<Window>().FirstOrDefault(o => o.IsActive);
if (win == null)
win = Application.Current.Windows.OfType<Window>().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);
}
}
}