winform 利用线程 实现窗体图片轮播

之前做一个餐饮点餐系统,需要在主界面实现自定义的一些图片的轮播,起初使用定时器,但是当子窗体打开,主线程转移,图片轮播就停止了。

随之使用线程来实现,当时查阅不少博客,与之契合的较少。所以贴上自己的代码,供后来者多一份参考~

线程的使用需要注意: 1、开始时确认线程的调用状态。  2、程序结束、或功能完成后,判断线程状态,并关闭。

using System.Windows.Forms;
using OrderFoodSystem.BLL;
using System.Threading;

namespace OrderFoodSystem
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            Form.CheckForIllegalCrossThreadCalls = false;       // 线程调用状态
            InitializeComponent();
        }

        Thread t;
        private void FrmMain_Load(object sender, EventArgs e) //FormLoad
        {
            t = new Thread(new ThreadStart(Runiamge));       //启动线程
            t.Start();
           foodInfoBLL fib = new foodInfoBLL();
            List foodlist = fib.outfoodlist(1);


            foreach (Control control in this.Controls)//遍历Form上的所有控件 
            {
                if (control is PictureBox)
                {
                    PictureBox pb = (PictureBox)control;
                    pb.AllowDrop = true;
                }
            }

     #region  推荐菜品图片轮播的实现

        public List foodPhoto = new List();     //声明一个list集合用来存放 需要轮播的图片路径
        private void btnFoodRecom_Click(object sender, EventArgs e)   //添加推荐图片
        {
            //t = new Thread(new ThreadStart(Runiamge));
            //t.Start();
            foodInfoBLL fib = new foodInfoBLL();
            List foodlist = fib.outfoodlist(1);
            for (int i = 0; i < foodlist.Count; i++)
            {
                foodPhoto.Add(foodlist[i].FoodPhoto);
            }
            foreach (Control picbox in panel1.Controls)
            {
                if (picbox is PictureBox)
                {
                    PictureBox pic = (PictureBox)picbox;
                    pic.SizeMode = PictureBoxSizeMode.StretchImage;

                }
            }
        }
        private void Runiamge()      //图片轮播
        {
            while (true)
            {
                for (int i = 0; i < foodPhoto.Count - 3; i++)
                {
                    //if (foodPhoto.Count == i - 3)
                    //{
                    //    i = 0;
                    //}
                    pictureBox1.Image = Image.FromFile(foodPhoto[i].ToString());
                    pictureBox2.Image = Image.FromFile(foodPhoto[i + 1]);
                    pictureBox3.Image = Image.FromFile(foodPhoto[i + 2]);
                    Thread.Sleep(1500);

                    pictureBox1.Image = null;
                }
            }
        }
   private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)   //窗体关闭时结束线程
        {
            if (t.ThreadState == ThreadState.Running) //判断线程是否处于运行状态
            {
                t.Abort();
            }

        }
        #endregion


你可能感兴趣的:(.NET平台内容)