接着上一篇,讲解一种构建控件较为简便的方法-用UserControl。
- 新建一个工程。并在resources下添加四张图片,并添加一个按钮。
- 在solutionExplorer中右键点击工程,选择add-userControl,增加一个名为BeeControl的用户控件。
下面对这个用户控件的操作就想是操作主窗体那样,可以随意拖入其他控件。因为要轮流显示不同的四张图片,因此需要一个定时器。只需往用户控件中拖一个定时器即可。设置下时间间隔(100),enabled为true。模仿上一篇中在定时器处理程序中添加同样的代码,注意这里的BackgroundImage指的是UserControl-BeeControl中的背景。
private int cell = 0;
private void animationTimer_Tick(object sender, EventArgs e)
{
cell++;
switch (cell)
{
case 1: BackgroundImage = Properties.Resources.Bee_animation_1; break;//这里的BackgroundImage指的是UserControl-BeeControl中的背景。
case 2: BackgroundImage = Properties.Resources.Bee_animation_2; break;
case 3: BackgroundImage = Properties.Resources.Bee_animation_3; break;
case 4: BackgroundImage = Properties.Resources.Bee_animation_4; break;
case 5: BackgroundImage = Properties.Resources.Bee_animation_3; break;
default: BackgroundImage = Properties.Resources.Bee_animation_2;
cell = 0; break;
}
}
3.同上一篇一样,按钮click时间中添加以下程序:
BeeControl control = null;
private void button1_Click(object sender, EventArgs e)
{
if (control == null)
{
control = new BeeControl() { Location = new Point(100, 100) };//实例化一个对象
Controls.Add(control);//向controls集合增加一个控件时,它会立即出现在窗体上
}
else
{
using (control)//利用using语句来确保从controls集合删除控件后会将其撤销
{
Controls.Remove(control);
}
control = null;
}
}
跟上一篇继承PictureBox所不同的是,这里BeeControl类中不需要撤销timer。因为用户控件窗体已经做了这个工作。
代码下载:
http://download.youkuaiyun.com/detail/u013480539/9668438