public partial class Form1 : Form
{
SaveFileDialog sfd = new SaveFileDialog();
OpenFileDialog ofd = new OpenFileDialog();
public string contents = string.Empty;
public Form1()
{
InitializeComponent();
this.Text = "Untitled";
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.Text != contents)
{
DialogResult dr = MessageBox.Show("Do You want to save the changes made to " + this.Text, "Save", MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.Yes)
{
sfd.Title = "Save";
if (SaveFile() == 0)
return;
else
{
richTextBox1.Text = "";
this.Text = "Untitled";
}
contents = "";
}
else if (dr == DialogResult.No)
{
richTextBox1.Text = "";
this.Text = "Untitled";
contents = "";
}
else
{
richTextBox1.Focus();
}
}
else
{
this.Text = "Untitled";
richTextBox1.Text = "";
contents = "";
}
}
private int SaveFile()
{
sfd.Filter = "Text Documents|*.txt";
sfd.DefaultExt = "txt";
if (sfd.ShowDialog() == DialogResult.Cancel)
{
richTextBox1.Focus();
return 0;
}
else
{
contents = richTextBox1.Text;
if (this.Text == "Untitled")
richTextBox1.SaveFile(sfd.FileName,RichTextBoxStreamType.PlainText);
else
{
sfd.FileName = this.Text;
richTextBox1.SaveFile(sfd.FileName,RichTextBoxStreamType.PlainText);
}
this.Text = sfd.FileName;
return 1;
}
}
private void OpenFile()
{
ofd.Filter = "Text Documents|*.txt";
if (ofd.ShowDialog() == DialogResult.Cancel)
richTextBox1.Focus();
else
{
richTextBox1.LoadFile(ofd.FileName, RichTextBoxStreamType.PlainText);
this.Text = ofd.FileName;
contents = richTextBox1.Text;
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (richTextBox1.Text != contents)
{
DialogResult dr = MessageBox.Show("Do You want to save the changes made to " + this.Text, "Save", MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.Yes)
{
SaveFile();
OpenFile();
}
else if (dr == DialogResult.No)
{
OpenFile();
}
else
{
richTextBox1.Focus();
}
}
else
OpenFile();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFile();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
sfd.Filter = "Text Documents|*.txt";
sfd.DefaultExt = "txt";
if (sfd.ShowDialog() == DialogResult.Cancel)
{
richTextBox1.Focus();
}
else
{
contents = richTextBox1.Text;
richTextBox1.SaveFile(sfd.FileName, RichTextBoxStreamType.PlainText);
this.Text = sfd.FileName;
}
}
当我们打开 Windows 记事本应用程序然后打开一个文件、更改它的内容并保存它时,它只是被保存而无需打开“保存文件”对话框。但是在我在上面创建的记事本程序中,在更改保存文件的内容后单击“保存”会打开“保存文件”对话框。虽然相同的文件名出现在保存文件对话框中,但在单击“保存”时会显示一条消息“相同的文件名已存在。您要替换它吗?”。这就是我要删除的内容,并将更改的内容直接保存到打开的文件中,而无需打开保存文件对话框。