C#winform打开图片文件夹列表自动显示
作者:野牛程序员:2023-12-29 11:17:39C#阅读 3196
使用C# WinForms 可以通过以下步骤实现打开图片文件夹并自动显示文件列表:
using System;
using System.IO;
using System.Windows.Forms;
namespace ImageFolderViewer
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void btnOpenFolder_Click(object sender, EventArgs e)
{
using (var folderDialog = new FolderBrowserDialog())
{
// 设置文件夹对话框的属性
folderDialog.Description = "选择图片文件夹";
folderDialog.ShowNewFolderButton = false;
// 打开文件夹对话框
DialogResult result = folderDialog.ShowDialog();
// 检查用户是否选择了文件夹
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderDialog.SelectedPath))
{
// 清空之前的图片列表
listBoxImages.Items.Clear();
// 获取所选文件夹中的所有图片文件
string[] imageFiles = Directory.GetFiles(folderDialog.SelectedPath, "*.jpg;*.jpeg;*.png;*.gif;*.bmp");
// 将图片文件添加到列表框中
foreach (string imagePath in imageFiles)
{
listBoxImages.Items.Add(Path.GetFileName(imagePath));
}
}
}
}
private void listBoxImages_SelectedIndexChanged(object sender, EventArgs e)
{
// 在此处添加显示选定图片的代码,可以使用PictureBox等控件来显示图片
// 示例:pictureBox.Image = Image.FromFile(Path.Combine(selectedFolderPath, listBoxImages.SelectedItem.ToString()));
}
}
}在这个例子中,有一个按钮 btnOpenFolder 用于打开文件夹对话框,一个列表框 listBoxImages 用于显示选定文件夹中的图片文件列表。在 listBoxImages_SelectedIndexChanged 方法中,可以添加代码来显示选定的图片,比如使用 PictureBox 控件。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C程序计算 5<<3和 5>>4的值
- 下一篇:桶排序和计数排序有什么区别
