winform C#屏幕右下角彈出消息框,自動消失

private void button2_Click(object sender, EventArgs e)
      {
         Form1 frmShowWarning = new Form1();//Form1爲要彈出的窗體(提示框),
            Point p = new Point(Screen.PrimaryScreen.WorkingArea.Width-frmShowWarning.Width, Screen.PrimaryScreen.WorkingArea.Height);
            frmShowWarning.PointToScreen(p);
            frmShowWarning.Location = p;
            frmShowWarning.Show();
            for (int i = 0; i <= frmShowWarning.Height; i++)
            {
                frmShowWarning.Location = new Point(p.X, p.Y - i);
                Thread.Sleep(10);//將線程沉睡時間調的越小升起的越快
            }
      }

如果要讓提示窗過一段時間慢慢的消失,則可以在Form1中放一個timer計時器,設定他執行的頻率爲2000,Form1的load事件中timer1.Enable=true,當此彈出框load過2秒後timer1開始工作,在timer1事件中代碼:

private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            for (int i = 0; i <= this.Height; i++)
            {
                Point p = new Point(this.Location.X, this.Location.Y + i);//彈出框向下移動消失
                this.PointToScreen(p);//即時轉換成屏幕座標
                this.Location = p;// new Point(this.Location.X, this.Location.Y + i);
                System.Threading.Thread.Sleep(10);//線程睡眠時間調的越小向下消失的速度越快。
                
            }
            this.Close();//記得關閉此彈出框哦。OK
        }

如果想讓彈出窗,過了半分鐘開始漸漸透明一直到關閉,又想在透明階段鼠標移上去彈出窗顯示不透明則操作如下:

1、在彈出窗上添加兩個timer控件。執行代碼如下:

timer2的事件中:

/// <summary>
        /// 
        /// 判斷鼠標是不是還在彈出框上,如果不是則timer1又可以開始工作了
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;//timer1停止工作
            this.Opacity = 1;//彈出窗透明度設置爲1,完全不透明
            if (System.Windows.Forms.Control.MousePosition.X < this.Location.X && System.Windows.Forms.Control.MousePosition.Y < this.Location.Y)//如下
            {
                timer1.Enabled = true;
                timer2.Enabled = false;
            }
        }

timer1的事件中代碼:

private void timer1_Tick(object sender, EventArgs e)
        {
            timer2.Enabled = false;//停止timer2計時器,
            if (this.Opacity > 0 && this.Opacity <= 1)//開始執行彈出窗漸漸透明
            {
                this.Opacity = this.Opacity - 0.05;//透明頻度0.05
            }
            if (System.Windows.Forms.Control.MousePosition.X >= this.Location.X && System.Windows.Forms.Control.MousePosition.Y >= this.Location.Y)//每次都判斷鼠標是否是在彈出窗上,使用鼠標在屏幕上的座標跟彈出窗體的屏幕座標做比較。
            {
                timer2.Enabled = true;//如果鼠標在彈出窗上的時候,timer2開始工作
                timer1.Enabled = false;//timer1停止工作。
            }
            if (this.Opacity == 0)//當透明度==0的時候,關閉彈出窗以釋放資源。
            {
                this.Close();
            }
        }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章