开发者

C# object sender - getting the Method from which it was called

I've got these Methods:

    private void button_Click(object sender, EventArgs e)
    {
          //Changes the Text in the RichBox, EXAMPLE:开发者_如何学C
          richtTextBox.Text = "Now Changed and calling Method richTextBox_TextChanged";
    }

And,

 private void richTextBox_TextChanged(object sender, EventArgs e)
 {
         //Wants something like that
         if(called from button_click)
         {
           //DO SOMETHING
         }
         else
         {
           //DO SOMETHING
         }
 }

How can I handle this, to know if it was called from the Button_click? Do I have to use the object sender to get informations? But how?

Hope u guys can help me


Just use a flag:

private bool _isInButtonClick;

private void button_Click(object sender, EventArgs e)
{
      try
      {
          _isInButtonClick = true;
          //Changes the Text in the RichBox, EXAMPLE:
          richtTextBox.Text = "Now Changed and calling Method richTextBox_TextChanged";
      }
      finally
      {
          _isInButtonClick = false;
      }
}


 private void richTextBox_TextChanged(object sender, EventArgs e)
 {
         if(_isInButtonClick)
         {
           //DO SOMETHING
         }
         else
         {
           //DO SOMETHING
         }
 }


private void richTextBox_TextChanged(object sender, EventArgs e)

Here sender is the richTextBox, not the button that changed the text.

You could go into the stack trace to discover if the button click is on the call stack, but that's overkill (like using a nuke to crack a walnut).

Add a flag (bool) to your form, set it to true in the button click, and check it in the TextChanged event, then at the end of the button click, set it to false again.

If you do this I would advise wrapping this signal logic in a class that implements IDispose and use it in using statements.

That said, are you sure you need this functionality?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜