c# - 图片框C#的随机输出图像

标签 c# winforms image random picturebox

我正在开发一个 Winform,其中有这个图片框。我有 52 张不同的图像,但只有 1 张图像将显示在这个特定的图片框中。我不太确定如何在不以 52 个 if 语句结束的情况下执行此操作。谁能帮我解决这个问题,因为我在编程方面还是个新手:)

我正在用 C# 编程

谢谢! :D

最佳答案

小例子:

// Controls:
// pictureBox1
// Dock: Fill
// SizeMode: StretchImage
// timer1

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Linq;

namespace RandomImg
{
    public partial class Form1 : Form
    {
        // List of files to show 
        private List<string> Files;

        public Form1()
        {
            InitializeComponent();
        }

        // StartUp 
        private void Form1_Load(object sender, EventArgs args)
        {
            // basic settings.
            var ext = new List<string> {".jpg", ".gif", ".png"};

            // we use same directory where program is.
            string targetDirectory = Directory.GetCurrentDirectory();

            // Here we create our list of files
            // New list
            // Use GetFiles to getfilenames
            // Filter unwanted stuff away (like our program)
            Files = new List<string>
                (Directory.GetFiles(targetDirectory, "*.*", SearchOption.TopDirectoryOnly)
                .Where(s => ext.Any(e => s.EndsWith(e))));

            // Create timer to call timer1_Tick every 3 seconds.
            timer1 = new System.Windows.Forms.Timer();
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Interval = 3000; // 3 seconds
            timer1.Start();

            // Show first picture so we dont need wait 3 secs.
            ChangePicture();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // Time to get new one.
            ChangePicture();
        }

        private void ChangePicture()
        {
            // Do we have pictures in list?
            if (Files.Count > 0)
            {
                // OK lets grab first one
                string File = Files.First();
                // Load it
                pictureBox1.Load(File);
                // Remove file from list
                Files.RemoveAt(0);
            }
            else
            {
                // Out of pictures, stopping timer
                // and wait god todo someting.
                timer1.Stop();
            }
        }
    }
}

关于c# - 图片框C#的随机输出图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16500176/

相关文章:

javascript - 如何让 &lt;script&gt; 与 Angular Controller 共享数据?

c# - 是否有可以单独为段着色的 WinForms 折线图控件?

javascript - 通过动态复选框立即过滤 SharePoint 列表(使用 C# 和/或 Ajax)

c# - 获取列表中的后续元素 C#

c# - 如何将 c# 日期时间变量插入 SQL Server

c# - 如何从 DateTimePicker 控件(Windows 窗体控件)中删除 "Today"按钮

c# - 如何在 C# 中为文本字段动态生成下拉选项?

html - 如何使用 CSS 创建动态大小的表单背景?

c# - 如何使用 Resources.resx 链接图像

html - div 中的图像在图像下方有额外的空间