C# WPF 建立渐隐窗口

需求:

一些无关紧要的提示信息,不显示出来怕用户一头雾水,但如果用对话框显示出来,用户又要动手把对话框关闭。不说别人,就是程序员自己测试时都觉得麻烦!

解决方案:

有两种选择

1. 选择是用 label 或文本框在界面显示消息,

2. 系统自动关闭消息提示的对话框

 

对于第2种选择,如果忽然关闭,感官效果可能有些突兀,可以尝试打开渐隐窗口,让它慢慢消失,既不突兀也不用麻烦用户。

代码:

 public partial class MessageBar : IMessageBox
    {
        public MessageBar(string msg, int timeOut)
            :base()
        {
            InitializeComponent();
            ApplyStyle();
            tbMsg.Text = msg;
            Timer timer = new Timer();//窗口停留显示
            timer.Interval = timeOut;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            //逐渐隐藏窗口,然后自动关闭
            Timer opacityTimer = new Timer();
            opacityTimer.Interval = 100;
            opacityTimer.Tick += new EventHandler(opacityTimer_Tick);
            opacityTimer.Start();

            ((Timer)sender).Stop();
        }

        void opacityTimer_Tick(object sender, EventArgs e)
        {
            this.Opacity -= 0.1;//透明度,初始值为1, 每次触发 Tick事件减 0.1
            if (this.Opacity <= 0.3) // 透明度小于 0.3 时直接关闭窗口
            {
                ((Timer)sender).Stop();
                this.Close();
            }
        }
    }

这里有两个定时器,一个是窗口停留的定时器,调用时可指定停留多长时间(ms),然后开始渐渐隐藏,即设置当前窗口的透明度,每100ms,透明度减0.1,透明度小于0.3时,用户基本看不见了,这时可以关闭窗口。

posted @ 2016-11-17 08:50  沐汐Vicky  阅读(1497)  评论(2编辑  收藏  举报