轻松实现WinForm的渐入渐出效果

 计时器timer是个很好用的控件,以下是在WinForm中实现一个web里面常用的渐入渐出效果。

  1namespace setOpacity
  2
  3{
  4
  5    public partial class Form1 : Form
  6
  7    {
  8
  9        public Form1()
 10
 11        {
 12
 13            InitializeComponent();
 14
 15            //状态初始化
 16
 17            this.Opacity = 0;
 18
 19           show = true;
 20
 21           // timer1.Interval = 100;
 22
 23            //设置timer的运行间隔
 24
 25            timer1.Enabled = true;
 26
 27        }

 28
 29 
 30
 31        //定义两个状态
 32
 33        public bool show = true;
 34
 35        public bool close = false;
 36
 37 
 38
 39        
 40
 41        /// <summary>
 42
 43        /// 计时器中需要定时间间隔完成的内容
 44
 45        /// </summary>
 46
 47        /// <param name="sender"></param>
 48
 49        /// <param name="e"></param>

 50
 51        private void timer1_Tick(object sender, EventArgs e)
 52
 53        {
 54
 55            if (show)
 56
 57            {
 58
 59                if (this.Opacity < 1)
 60
 61                {
 62
 63                    this.Opacity = Opacity + 0.1;
 64
 65                }

 66
 67                else
 68
 69                {
 70
 71                    show = false;
 72
 73                    this.timer1.Enabled = false;
 74
 75                }

 76
 77            }

 78
 79 
 80
 81            if (close)
 82
 83            {
 84
 85                if (this.Opacity > 0.1)
 86
 87                {
 88
 89                    this.Opacity = this.Opacity - 0.1;
 90
 91                }

 92
 93                else
 94
 95                {
 96
 97                    close = false;
 98
 99                    this.timer1.Enabled = false;
100
101                    this.Close();
102
103                }

104
105            }

106
107        }

108
109 
110
111 
112
113        /// <summary>
114
115        /// 重写Form的关闭事件
116
117        /// </summary>
118
119        /// <param name="e"></param>

120
121        protected override void OnClosing(CancelEventArgs e)
122
123        
124
125            base.OnClosing(e);    
126
127            if (this.Opacity > 0.1)
128
129            {
130
131                e.Cancel = true;
132
133            }

134
135            timer1.Enabled = true;
136
137            close = true;
138
139        }

140
141    }

142
143}

144
145

运行示例:http://newhost.byhh.net/f/DotNet/1181880733/setOpacity.exe
值得一提的是,timer是内部多线程。这杨我们可以方便的实现诸如可控制的动态数字之类的功能。有兴趣的朋友可以试一下。

posted on 2007-06-15 22:46  J.D Huang  阅读(877)  评论(2编辑  收藏  举报