C#--第12周實驗--任務2(設計一個窗體)--開啟對話方塊
阿新 • • 發佈:2019-01-25
/* (程式頭部註釋開始) * 程式的版權和版本宣告部分 * Copyright (c) 2011, 煙臺大學計算機學院學生 * All rights reserved. * 檔名稱:訊息對話方塊 * 作 者: 雷恆鑫 * 完成日期: 2012 年 11 月 12 日 * 版 本 號: V1.0 * 對任務及求解方法的描述部分 * 輸入描述:在窗體上增加一個按鈕,並設定按鈕顯示文字為“結束程式”。單擊該按鈕顯示如下訊息框,若選擇是,則結束程式,否則只是關閉訊息框。 * 關鍵程式碼: DialogResult result = MessageBox.Show("確定要結束程式嗎?[Yes|No]", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2); if (result==DialogResult.Yes) { Application.Exit(); } * 問題描述: * 程式輸出: * 程式頭部的註釋結束 */ 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; using System.IO; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.pictureBox1.Image = Image.FromFile("風景1.jpg");//動態載入圖片 this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;//設定圖片顯示方式 this.pictureBox2.Image = Image.FromFile("風景2.jpg");//動態載入圖片 this.pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;//設定圖片顯示方式 toolTip1.SetToolTip(pictureBox1, "這是山東省陽谷縣的風光"); toolTip1.SetToolTip(pictureBox2, "這是山東省陽谷縣武松打虎的自然風光"); } private void button1_Click(object sender, EventArgs e) { if (DialogResult.Yes == MessageBox.Show("確定要結束程式嗎?[Yes|No]", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3)) { Application.Exit(); } } private void button2_Click(object sender, EventArgs e) { this.saveFileDialog1.Filter = "*.txt|*.txt"; this.saveFileDialog1.ShowDialog(); string file = this.saveFileDialog1.FileName; if (string.IsNullOrEmpty(file)) return; //以下為寫字元到文字檔案,需要新增System.IO引用 //建立一個檔案流 FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write); //建立一個StreamWriter物件 StreamWriter sw = new StreamWriter(fs); textBox1.SelectAll(); sw.Write(textBox1.SelectedText); //釋放StreamWriter物件,檔案流物件 sw.Dispose(); fs.Dispose(); } private void button3_Click(object sender, EventArgs e) { this.openFileDialog1.Filter = "*.txt|*.txt"; this.openFileDialog1.ShowDialog(); string file = this.openFileDialog1.FileName; if (string.IsNullOrEmpty(file)) return; //以下為寫字元到文字檔案,需要新增System.IO引用 //建立一個檔案流 FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); //建立一個StreamWriter物件 StreamReader sr = new StreamReader(fs); this.textBox1.Text = sr.ReadToEnd(); //釋放StreamWriter物件,檔案流物件 sr.Dispose(); fs.Dispose(); } } }
執行結果: