我在表单关闭时声明了一个formClosing事件过程 这是我的代码。我正在使用c#设计一个记事本,在关闭表单或我的记事本应用程序之前,它应该询问用户是否要保存它。
private void Form13_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.Text == "Untitled-FileEditor")
{
if (richTextBox1.Text.Length > 0)
{
DialogResult dr = MessageBox.Show("Do u want to save changes to untitled", "FileEditor", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
saveFileDialog1.FileName = "NewText";
saveFileDialog1.Filter = "Text Files(*.txt)|*.txt";
DialogResult d = saveFileDialog1.ShowDialog();
if (d == DialogResult.OK)
{
string TextFilePath = saveFileDialog1.FileName;
richTextBox1.SaveFile(TextFilePath, RichTextBoxStreamType.PlainText);
richTextBox1.Text = "";
}
}
if (dr == DialogResult.No)
{
//richTextBox1.Text = "";
this.Close();
}
}
else if (richTextBox1.Text.Length == 0)
{ this.Close(); }
}
else if (this.Text != "Untitled-FileEditor")
{
if (richTextBox1.Modified)
{
DialogResult dr = MessageBox.Show("Do u want to save changes to " + openFileDialog1.FileName, "FileEditor", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
saveFileDialog1.FileName = "NewText";
saveFileDialog1.Filter = "Text Files(*.txt)|*.txt";
DialogResult d = saveFileDialog1.ShowDialog();
if (d == DialogResult.OK)
{
string TextFilePath = saveFileDialog1.FileName;
richTextBox1.SaveFile(TextFilePath, RichTextBoxStreamType.PlainText);
richTextBox1.Text = "";
}
}
if (dr == DialogResult.No)
{
//richTextBox1.Text = "";
this.Close();
}
}
if (!richTextBox1.Modified)
{
this.Text = "Untitled-FileEditor";
//richTextBox1.Text = "";
this.Close();
}
}
}
显示错误 - System.Windows.Forms.dll中出现未处理的“System.InvalidOperationException”类型异常
附加信息:跨线程操作无效:控制'richTextBox1'从其创建的线程以外的线程访问。
答案 0 :(得分:0)
这意味着您尝试访问/修改来自其他线程的数据,而不是允许的数据。
请尝试:
richtextBox1.Invoke(new Action(richtextBox1.Text = "sample text")); //just a sample
而不是richtextBox1.Text = "sample text"
,而是编写出现错误的行的代码。
也许您应该在 OnClosed
事件中执行您的操作:
protected override void OnClosed(EventArgs e)
{
//your code here
base.OnClosed(e);
}