
以下是一个简单的示例代码:
public partial class Form1 : Form
{
private int speed = 5// 控件每次移动的速度
private int direction = 1// 控件移动的方向
private Timer timer1// 定时器控件
private PictureBox pictureBox1// PictureBox 控件
public Form1()
{
InitializeComponent()
// 初始化 PictureBox 控件
pictureBox1 = new PictureBox()
pictureBox1.Location = new Point(0, 100)// 控件初始位置
pictureBox1.Image = Image.FromFile("picture.jpg")// 控件的图片
// 初始化定时器控件
timer1 = new Timer()
timer1.Interval = 30// 定时器的时间间隔
timer1.Tick += new EventHandler(timer1_Tick)
timer1.Start()
this.Controls.Add(pictureBox1)// 将 PictureBox 添加到窗体中
}
// 定时器每次触发时执行的方法
private void timer1_Tick(object sender, EventArgs e)
{
// 判断控件是否到达窗体边界,如果到达则改变方向
if (pictureBox1.Right >= this.ClientSize.Width &&direction == 1)
{
direction = -1
}
else if (pictureBox1.Left <= 0 &&direction == -1)
{
direction = 1
}
// 移动控件的位置
pictureBox1.Left += speed * direction
}
}
在该示例代码中,每次 Timer 控件触发后,判断 PictureBox 控件是否到达窗体边界,如果到达则改变方向,然后移动控件的位置。由于定时器的时间间隔很短,因此控件的运动看起来就像是重复从左至右不断循环运动。
Label lb = new Label()lb.Text = "NewLable"
lb.Location = new Point(70, 50)
lb.Name = "LableNew"
lb.BackColor = Color.Purple
this.pictureBox1.Controls.Add(lb)
原理就是在原有的pictureBox1上新add了个新的控件 容器是原来的pictureBox1
有问题Hi我~
PictureBox p = new PictureBox()//实例化一个照片框p.BackColor = Color.Red
this.Controls.Add(p)//添加到当前窗口集合中
p.Width = 200
p.Height = 200
//属性都要自己设置哟!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)