给你写了代码,你可以根据需要自己修改,下面有两个图像的路径要改成自己盘里图像的路径。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ImageListAndLabelTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Label label1;
ImageList imageList;
//图像计数
int nImageNum = -1;
private void Form1_Load(object sender, EventArgs e)
{
label1 = new Label();
imageList = new ImageList();
label1.AutoSize = false;
label1.BorderStyle = BorderStyle.Fixed3D;
//放置label1的位置
label1.Bounds = new Rectangle(0, 0, 60, 40);
label1.BackColor = Color.Blue;
this.Controls.Add(label1);
//这里可以更改图像在窗体上的显示方式
this.BackgroundImageLayout = ImageLayout.Center;
//添加两个鼠标事件,一个是鼠标停留事件,另一个是鼠标点击事件。
label1.MouseHover += new EventHandler(label1_MouseHover);
label1.MouseClick += new MouseEventHandler(label1_MouseClick);
//设置imageList中图像的显示大小
this.imageList.ImageSize = new Size(200, 200);
//加载两幅图像,请更改为自己磁盘里图像的路径
AddImagesToImageList("E:\\无命名.jpg");
AddImagesToImageList("E:\\键盘.png");
//启动时显示图像
ShowNextImage();
}
void label1_MouseClick(object sender, MouseEventArgs e)
{
this.ShowNextImage();
}
void label1_MouseHover(object sender, EventArgs e)
{
label1.Cursor = Cursors.Hand;
}
//添加一幅图像到imageList中
private bool AddImagesToImageList(string strImageFilePath)
{
try
{
this.imageList.Images.Add(Image.FromFile(strImageFilePath));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
nImageNum++;
return true;
}
//显示下一幅图像
private void ShowNextImage()
{
if (nImageNum == -1)
return;
label1.Image = imageList.Images[nImageNum];
this.BackgroundImage = imageList.Images[nImageNum++];
if (nImageNum == imageList.Images.Count)
nImageNum = 0;
}
}
}