我正在制作一个文本编辑器,我想在表单标题中显示当前打开文件的名称(就像记事本一样,它显示“无标题 - 记事本”或““文件 - 记事本”)。
我假设这是使用 SaveFileDialog 和 OpenFileDialog 完成的,所以我将发布我当前的代码。
打开文件:
private void OpenFile()
{
NewFile();
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (ofd.ShowDialog() != DialogResult.OK) return;
StreamReader sr = null;
try
{
sr = new StreamReader(ofd.FileName);
this.Text = string.Format("{0} - Basic Word Processor", ofd.FileName);
richTextBoxPrintCtrl1.Text = ofd.FileName;
richTextBoxPrintCtrl1.Text = sr.ReadToEnd();
filepath = ofd.FileName;
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
catch
{
}
finally
{
if (sr != null) sr.Close();
}
保存存档
private void SaveFileAs()
{
SaveFileDialog sfdSaveFile = new SaveFileDialog();
sfdSaveFile.Title = "Save File";
sfdSaveFile.FileName = "Untitled";
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (sfdSaveFile.ShowDialog() == DialogResult.OK)
try
{
filepath = sfdSaveFile.FileName;
SaveFile();
this.Text = string.Format("{0} - Basic Word Processor", sfdSaveFile.FileName);
}
catch (Exception exc)
{
}
void SetWindowTitle(string fileName) {
this.Text = string.Format("{0} - Basic Text Editor", System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog.Filename));
如何获取文件名并将其放在表单的标题中(就像记事本一样,文件名后跟文本编辑器的名称)。