C#——《C#语言程序设计》实验报告——Windows桌面编程文件与流——简易记事本
一、實驗目的
二、實驗內容
(1)設計界面,向窗體添加下拉式菜單、多格式文本框(RichTextBox)。
(2)依次為“文件”下的“新建”、“打開”、“保存”菜單項的Click事件添加事件處理函數。可以使用路由命令。
(3)添加“格式”工具欄,可以設置所有文字的粗體、斜體、大小、顏色等樣式。
(4)實現文本文件的打開、編輯和保存功能;
提示
1、窗口可用DockPanel進行布局,讓菜單和工具欄都位于頂部,即:
DockPanel.Dock="Top"2、文本文件的編輯可以使用TextBox控件。
3、使用命令綁定,讓菜單項和工具欄同時與一個操作相關聯。
在MainWindow.xaml的Window標簽下加:
??? <Window.CommandBindings><CommandBinding Command="ApplicationCommands.New" Executed="NewCommand_Executed"/><CommandBinding Command="ApplicationCommands.Open" Executed="OpenCommand_Executed"/><CommandBinding Command="ApplicationCommands.Save" Executed="SaveCommand_Executed"/></Window.CommandBindings>在菜單項添加:
????????<MenuItem Header="新建(_N)" Command="New"/>在工具欄添加:
??????????? <Button Content="新建" Command="New"/>就可綁定命令。同時Ctrl+O等鍵盤組合也默認與Open命令相綁定。
其中NewCommand_Executed需要作為一個事件響應方法來實現。
4、添加bool類型_saved字段,標記當前內容是否已保存。(文本格式不屬于文件內容,修改格式不會導致_saved字段的改變)
5、打開文件時,彈出打開文件對話框,操作代碼如下:
?? OpenFileDialog dlg = new OpenFileDialog();dlg.DefaultExt = "*.txt";dlg.Filter = "Text Files (*.txt)|*.txt";bool? result = dlg.ShowDialog();if (result == true){string fileName = dlg.FileName;}自此可對該文件名進行操作。
6、保存文件時,實際可實現“另存為”功能。彈出保存文件對話框,操作代碼如下:
SaveFileDialog saveFileDialog = new SaveFileDialog();saveFileDialog.Filter = "文本文件|*.txt|所有文件|*.*";saveFileDialog.FilterIndex = 0;bool? result = saveFileDialog.ShowDialog();if (result == true){string strFile = saveFileDialog.FileName;}自此可對該文件名進行操作。
7、可以根據自己的想法,添加更加豐富的功能。
源代碼?
XAML
<Window x:Class="Homework11.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:Homework11"mc:Ignorable="d"Title="記事本" Height="450" Width="800"><Window.CommandBindings><CommandBinding Command="ApplicationCommands.New" Executed="NewCommand_Executed"/><CommandBinding Command="ApplicationCommands.Open" Executed="OpenCommand_Executed"/><CommandBinding Command="ApplicationCommands.Save" Executed="SaveCommand_Executed"/><CommandBinding Command="ApplicationCommands.Print" Executed="PrintCommand_Executed"/></Window.CommandBindings><DockPanel><DockPanel.Resources><Style TargetType="{x:Type Button}" x:Key="formatTextStyle"><Setter Property="FontFamily" Value="Palatino Linotype"></Setter><Setter Property="Width" Value="30"></Setter><Setter Property="FontSize" Value ="14"></Setter><Setter Property="CommandTarget" Value="{Binding ElementName=MainTextBox}"></Setter></Style><Style TargetType="{x:Type Button}" x:Key="formatImageStyle"><Setter Property="Width" Value="30"></Setter><Setter Property="CommandTarget" Value="{Binding ElementName=MainTextBox}"></Setter></Style></DockPanel.Resources><Menu x:Name="MainMenu" DockPanel.Dock="Top"><MenuItem Header="文件"><MenuItem Header="新建(_N)" Command="New"/><MenuItem Header="打開(_O)" Command="Open"/><MenuItem Header="保存(_S)" Command="Save"/><MenuItem Header="打印(_P)" Command="Print"/></MenuItem><MenuItem Header="格式"><MenuItem Header="自動換行(_W)"/><MenuItem Header="字體(_F)"/></MenuItem></Menu><ToolBar x:Name="MainToolBar" DockPanel.Dock="Top"><Button Style="{StaticResource formatImageStyle}" Command="New" ><Image Source="Images/New.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="Open"><Image Source="Images/Open.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="Save"><Image Source="Images/Save.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="Print"><Image Source="Images/Print.png"></Image></Button></ToolBar><!-- This tool bar contains all the editing buttons. --><ToolBar Name="mainToolBar" Height="30" DockPanel.Dock="Top"><Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Cut" ToolTip="Cut"><Image Source="Images/EditCut.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Copy" ToolTip="Copy"><Image Source="Images/EditCopy.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Paste" ToolTip="Paste"><Image Source="Images/EditPaste.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Undo" ToolTip="Undo"><Image Source="Images/EditUndo.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Redo" ToolTip="Redo"><Image Source="Images/EditRedo.png"></Image></Button><Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleBold" ToolTip="Bold"><Image Source="Images/EditBold.png"></Image></Button><Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleItalic" ToolTip="Italic"><Image Source="Images/EditItalic.png"></Image></Button><Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleUnderline" ToolTip="Underline"><Image Source="Images/EditUnderline.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.IncreaseFontSize" ToolTip="Grow Font"><Image Source="Images\CharacterGrowFont.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.DecreaseFontSize" ToolTip="Shrink Font"><Image Source="Images\CharacterShrinkFont.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.ToggleBullets" ToolTip="Bullets"><Image Source="Images\ListBullets.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.ToggleNumbering" ToolTip="Numbering"><Image Source="Images/ListNumbering.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignLeft" ToolTip="Align Left"><Image Source="Images\ParagraphLeftJustify.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignCenter" ToolTip="Align Center"><Image Source="Images\ParagraphCenterJustify.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignRight" ToolTip="Align Right"><Image Source="Images\ParagraphRightJustify.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignJustify" ToolTip="Align Justify"><Image Source="Images\ParagraphFullJustify.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.IncreaseIndentation" ToolTip="Increase Indent"><Image Source="Images\ParagraphIncreaseIndentation.png"></Image></Button><Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.DecreaseIndentation" ToolTip="Decrease Indent"><Image Source="Images\ParagraphDecreaseIndentation.png"></Image></Button></ToolBar><RichTextBox x:Name="MainTextBox" DockPanel.Dock="Top" Height="300" TextChanged="MainTextBox_TextChanged" AcceptsTab="True"><FlowDocument><Paragraph><Run></Run></Paragraph></FlowDocument></RichTextBox><StatusBar DockPanel.Dock="Bottom"><TextBlock x:Name="MainStatusBar"></TextBlock></StatusBar></DockPanel></Window>CS
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Win32;namespace Homework11 {/// <summary>/// MainWindow.xaml 的交互邏輯/// </summary>public partial class MainWindow : Window{private bool _saved;private string title {set { Title = value; }get { return Title; }}public MainWindow(){InitializeComponent();}private void NewCommand_Executed(object sender, ExecutedRoutedEventArgs e){_saved = false;TextRange range;range = new TextRange(MainTextBox.Document.ContentStart, MainTextBox.Document.ContentEnd);range.Text = "";}private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e){OpenFileDialog dlg = new OpenFileDialog();dlg.DefaultExt = "*.txt";dlg.Filter = "Text Files (*.txt)|*.txt";bool? result = dlg.ShowDialog();string str=null;if (result == true){string _fileName = dlg.FileName;TextRange range;FileStream fStream;if (File.Exists(_fileName)){title = _fileName;range = new TextRange(MainTextBox.Document.ContentStart, MainTextBox.Document.ContentEnd);fStream = new FileStream(_fileName, FileMode.OpenOrCreate);range.Load(fStream, DataFormats.XamlPackage);fStream.Close();}}}private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e){if (_saved) {return;}SaveFileDialog saveFileDialog = new SaveFileDialog();saveFileDialog.Filter = "文本文件|*.txt|所有文件|*.*";saveFileDialog.FilterIndex = 0;bool? result = saveFileDialog.ShowDialog();if (result == true){string strFile = saveFileDialog.FileName;TextRange range;FileStream fStream;range = new TextRange(MainTextBox.Document.ContentStart, MainTextBox.Document.ContentEnd);fStream = new FileStream(strFile, FileMode.Create);range.Save(fStream, DataFormats.XamlPackage);fStream.Close();_saved = true;MainStatusBar.Text = "保存到" + strFile;}}private void PrintCommand_Executed(object sender, ExecutedRoutedEventArgs e){PrintDialog pd = new PrintDialog();if ((pd.ShowDialog() == true)){//use either one of the belowpd.PrintVisual(MainTextBox as Visual, "printing as visual");pd.PrintDocument((((IDocumentPaginatorSource)MainTextBox.Document).DocumentPaginator), "printing as paginator");}}private void MainTextBox_TextChanged(object sender, TextChangedEventArgs e){_saved = false;}private void LineCommand_Executed(object sender, ExecutedRoutedEventArgs e){}private void FontSelectCommand_Executed(object sender, ExecutedRoutedEventArgs e){}} }運行結果
三、實驗心得與體會
參考文章
https://docs.microsoft.com/zh-cn/dotnet/framework/wpf/controls/richtextbox-overview#save-load-and-print-richtextbox-content
https://blog.csdn.net/u011389706/article/details/55805476
https://blog.csdn.net/weixin_43272781/article/details/106284772
https://www.jianshu.com/p/9c30b5097a3f
https://www.cnblogs.com/arxive/p/5725570.html
總結
以上是生活随笔為你收集整理的C#——《C#语言程序设计》实验报告——Windows桌面编程文件与流——简易记事本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#——WPF的菜单栏、工具栏、状态栏D
- 下一篇: C#——《C#语言程序设计》实验报告——