简体   繁体   English

当文本从方法内部更改时,不会触发RichTextBox.TextChanged事件

[英]RichTextBox.TextChanged event not firing when the text changes from inside a method

Ok, this one's easy for you guys, I basically have a C# winform app, all it has is a RichTextBox, and there's a class called Terminal, inside that class there's a RichTextBox data memeber and some other things, I pass the RichTextBox of my form to the constructor of Terminal, like this: 好的,这对您来说很容易,我基本上有一个C#winform应用程序,它拥有一个RichTextBox,还有一个名为Terminal的类,在该类中有一个RichTextBox数据成员和其他一些东西,我通过了RichTextBox提交给Terminal的构造函数,如下所示:

public Terminal(RichTextBox terminalWindow)
{
  this.terminalWindow = terminalWindow;
  CommandsBuffer = new List<string>();
  currentDirectory = homeDirectory;
  this.terminalWindow.TextChanged += new EventHandler(terminalWindow_TextChanged);
  InsertCurrentDirectory();
}

this is what I'm doing in the InsertCurrentDirectory() method: 这是我在InsertCurrentDirectory()方法中所做的事情:

private void InsertCurrentDirectory()
{
  terminalWindow.Text = terminalWindow.Text.Insert(0, currentDirectory);
  terminalWindow.Text = terminalWindow.Text.Insert(terminalTextLength, ":");
  terminalWindow.SelectionStart = terminalTextLength + 1;
}

As you can see I've registered the event before calling this method, but the problem is, the event is not firing even though I'm changing the text from inside this method. 如您所见,在调用此方法之前,我已经注册了该事件,但是问题是,即使我正在从此方法内部更改文本,该事件也不会触发。 But it actually fired when I changed the text in the constructor right after registering the event, like this for example: 但是当我在注册事件后立即在构造函数中更改文本时,它实际上会触发,例如:

public Terminal(RichTextBox terminalWindow)
{
  // ...  
  this.terminalWindow.TextChanged += new EventHandler(terminalWindow_TextChanged);
  this.terminalWindow.Text = "the event fired here"; 
}

This is the TextChanged event just in case you wanna know what's in it: 这是TextChanged事件,以防万一您想知道其中的内容:

void terminalWindow_TextChanged(object sender, EventArgs e)
{
  terminalTextLength = terminalWindow.Text.Length;
}

why did this happen? 为什么会这样? why didn't the event fire from inside the method? 为什么事件没有从方法内部触发? how can i fire it? 我该如何射击?

Thanks. 谢谢。

Probably you create your Terminal class inside your form constructor (After the InitializeComponenet). 可能是在窗体构造函数中创建了Terminal类(在InitializeComponenet之后)。
At this point in time the form handle and all the handles for your controls exist only in the framework infrastucture, but not in the windows system and thus no message (TextChanged) will be fired. 此时,表单句柄和控件的所有句柄仅存在于框架基础结构中,而不存在于Windows系统中,因此不会触发任何消息(TextChanged)。

If you create your Terminal class inside the Form_Load event the TextChanged of the RichTextBox will be called without problems. 如果您在Form_Load事件中创建Terminal类,则RichTextBox的TextChanged将被调用而不会出现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM