使用openfiledialog打开图片文件,并使其在picturebox控件中显示,添加listbox列表框控件,添加多个文件后,点击列表框中的文件名,使对应的图片显示在picturebox控件中
时间: 2024-09-25 12:12:29 浏览: 29
要实现这个功能,你需要使用Windows Forms库中的OpenFileDialog、PictureBox和ListBox控件。首先,确保已导入System.Windows.Forms命名空间。下面是步骤:
1. **创建窗体和控件**:
- 在Form上拖动一个PictureBox(PictureBox)用于显示图片,一个OpenFileDialog(OpenFileDialog)控件用于选择图片,以及一个ListBox(ListBox)控件用于显示文件名。
2. **设置OpenFileDialog属性**:
- 设置OpenFileDialog的Filter属性以限制只显示图像文件(如`.jpg`, `.png`, `.gif`等):
```csharp
openFileDialog.Filter = "Image Files (*.jpg;*.jpeg;*.png;*.gif)|*.jpg;*.jpeg;*.png;*.gif";
```
3. **添加事件处理程序**:
- 当用户点击OpenFileDialog的"Open"按钮时,调用OpenFile()方法:
```csharp
private void openFileDialog_FileOk(object sender, EventArgs e)
{
// 事件处理逻辑
}
```
4. **OpenFile()方法**:
- 在此方法中,读取选定的文件并将其加载到PictureBox:
```csharp
private void OpenFile()
{
if (openFileDialog.FileName != "")
{
pictureBox.Image = Image.FromFile(openFileDialog.FileName);
listBox.Items.Add(openFileDialog.FileName); // 添加文件名到ListBox
}
}
```
5. **ListBox双击事件**:
- ListBox的DoubleClick事件允许你直接在选中的文件上显示图片:
```csharp
private void listBox_DoubleClick(object sender, EventArgs e)
{
pictureBox.Image = Image.FromFile(listBox.SelectedItem.ToString());
}
```
6. **最后记得添加事件绑定**:
- 将上述方法绑定到相应的事件上:
```csharp
openFileDialog.Click += new System.EventHandler(openFileDialog_Click);
listBox.SelectedIndexChanged += new EventHandler.listBox_SelectedIndexChanged);
```
完整示例代码:
```csharp
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void openFileDialog_Click(object sender, EventArgs e)
{
OpenFile();
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox.SelectedIndex != -1)
pictureBox.Image = Image.FromFile(listBox.SelectedItem.ToString());
}
private void OpenFile()
{
openFileDialog.ShowDialog();
if (openFileDialog.FileName != "")
{
pictureBox.Image = Image.FromFile(openFileDialog.FileName);
listBox.Items.Add(openFileDialog.FileName);
}
}
}
```
阅读全文