复制后,需要修改的代码:
1、图片文件夹路劲:string folderPath = "C:\\Users\\Administrator\\Desktop\\images";
2、项目命名空间:namespace BuildAction
全窗口代码:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.IO;
- using System.Threading;
-
-
- namespace BuildAction
- {
- public partial class Form1 : Form
- {
- private string[] imageFiles; // 存储图片文件路径
- private int currentIndex = 0; // 当前显示的图片索引
- private Thread rotateThread; // 轮播线程
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void StartRotate()
- {
- // 读取指定文件夹下的所有图片
- string folderPath = "C:\\Users\\Administrator\\Desktop\\images";
- imageFiles = Directory.GetFiles(folderPath, "*.png", SearchOption.TopDirectoryOnly);
- rotateThread = new Thread(() =>
- {
- while (true)
- {
- // 显示下一张图片
- currentIndex = (currentIndex + 1) % imageFiles.Length;
- this.Invoke(new Action(() =>
- {
- pictureBox1.Image = Image.FromFile(imageFiles[currentIndex]);
- }));
-
- // 等待 2 秒后切换图片
- Thread.Sleep(2000);
- }
- });
- rotateThread.IsBackground = true;
- rotateThread.Start();
- }
-
- private void StopRotate()
- {
- if (rotateThread != null && rotateThread.IsAlive)
- {
- rotateThread.Abort();
- }
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- // 开始轮播
- StartRotate();
- }
-
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- StopRotate();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- MessageBox.Show("测试多线程是否堵塞", "提醒");
- }
- }
- }