新建项目,添加PictureBox,Button控件

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open photo";
            dlg.Filter = "jpg files (*.jpg)|*.jpg"
                            + "|All files (*.*)|*.*";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    pictureBox1.Image = new Bitmap(dlg.OpenFile());
                }
                catch(ArgumentException ex)
                {
                    MessageBox.Show("Unable to load file:" + ex.Message);
                    pictureBox1.Image = null;
                }
            }
            dlg.Dispose();
        }
    }
}

运行结果:

Windows Forms 起步(2)

Windows Forms 起步(2)

相关文章: