我想利用visual studio 平台编写一个小程序,用c#来实现,但是遇到了困难,如何利用picturebox来显示?我想设置一个按钮,单击时让picturebox显示图片。要怎么办啊?高手求救一下!在输入图片路径时出错,要怎么解决呢?(要详细代码!)
(1)新建一个C#窗体项目,项目名为showPicture,在Form1上添加一个Picturebox控件和两个按钮。
(2)添加代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace showPicture
{
public partial class Form1:Form
{
public Form1()
{
InitializeComponent();
}
private string pathname=string.Empty;//定义路径名变量
private void button1_Click(object sender,EventArgs e)//打开方法
{
OpenFileDialog file=new OpenFileDialog();
file.InitialDirectory=".";
file.Filter="所有文件(*.*)|*.*";
file.ShowDialog();
if(file.FileName!=string.Empty)
{
try
{
pathname=file.FileName;//获得文件的绝对路径
this.pictureBox1.Load(pathname);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void button2_Click(object sender,EventArgs e)//保存方法
{
SaveFileDialog save=new SaveFileDialog();
save.ShowDialog();
if(save.FileName!=string.Empty)
{
pictureBox1.Image.Save(save.FileName);
}
}
}
}
(3)显示效果
模式显示。
(4)保存方法调用效果。