如果用户进行选择并单击确认按钮

时间:2022-04-22 08:34:58

  对话框也是一种窗体,凡是挪用对对话框相关类型的ShowDialog要领来弹出对话框,当用户*对话框后,该要领会返回一个DialogResult枚举值,通过该值就可以判断用户采纳了什么操纵,例如单击确认按钮后,对话框*,showDialog要领返回DialogResult.ok,更具返回值就能知道确认了操纵。

  FileDialog类供给了选择文件对话框的根基布局,他是一个抽象类,并派生出两个子类——OpenFileDialog和SaveFialeDialog

  OpenDialog用于打开文件,SaveFialeDialog用于生存文件是选新文件夹。打开文件对话框应该选择已存在的文件,所以通过CheckFileExists属性控制是否查抄文件的存在性,默认为True,应为打开不存在的文件没有意义。在使用SaveFileDialog来选择新文件的文件名,有时候会遇到生存的文件已经存在的情况,所以OverwritePrompt属性应该为True,当生存的文件存在的情况下提示用户是否要笼罩现有文件。

  Filter属性是指定在选择文件对哈框中应该显示那些文件。用字符串暗示。

文本文件(*.txt)|*.txt  (|  标记,管道标记,分隔断绝分手)

  在选择完成后,单击“确认按钮”*对话框,可以从FileName属性获得文件名字,该属性是返回的文件全部路径。

  对付OpenFileDialog来说,Multiselect属性为Ture,撑持选择多个文件,可以从FileNames属性中得到一个string数组,代表用户已经选择的文件列表。

例如:OpenFileDialog和SaveFileDialog对话框的使用

在打开按钮Click事件添加

private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //显示文件名 label1.Text = openFileDialog1.FileName; //加载图片 try { using (System.IO.FileStream Stream = System.IO.File.Open(openFileDialog1. FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { //创建图像 Image img = Image.FromStream(Stream); //在pictureBox中显示图像 pictureBox1.Image = img; //*文件流,,释放资源 Stream.Close(); } } catch (Exception ex) { label1.Text = ex.Message;//显示信息 } } }

  首先电泳ShowDialog要领显示选择文件的对话框,如果用户进行选择并单击确认按钮,返回DialogResult.OK就从FileName属性中得到选择文件的路径。通过File类的静态要领Open打开文件,返回文件流

,在文件流根本上创建Image东西,显示在PictureBox控件中。

在生存Click事件中添加

private void button2_Click(object sender, EventArgs e) { if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //筹备写入文件 System.IO.FileStream StreamOut = null; try { StreamOut = new System.IO.FileStream(saveFileDialog1.FileName, System.IO.FileMode.OpenOrCreate, System. IO.FileAccess.Write, System.IO.FileShare.Read); using (Bitmap bmp = new Bitmap(100, 100)) { Graphics g = Graphics.FromImage(bmp); //填充配景 g.Clear(Color.DarkBlue); //填充圆形区域 g.FillEllipse(Brushes.Yellow, new Rectangle(0, 0, bmp.Width, bmp.Height)); //释放东西 g.Dispose(); //将图像内容写入文件流 bmp.Save(StreamOut, System.Drawing.Imaging.ImageFormat.Png); } //显示生存告成 MessageBox.Show("图像文件生存告成。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { //释放文件流占用的资源 if (StreamOut != null) { StreamOut.Close(); StreamOut.Dispose(); } } } }

如果用户进行选择并单击确认按钮