0

is there a way to remove an event handler while the program is running?

textBox1.TextChanged += (s, a) =>
            {
                JRPC.SetMemory(rgh, 0xc035261d, reverseBytes(textBox1.Text));
                JRPC.SetMemory(rgh, 0xc035261c, getBytes(Encoding.ASCII.GetBytes(textBox1.Text + "\0")));
            };

I have the code above to real time edit the players Gamertag on Xbox. When a checkbox it checked it will discover the event handler. but when I uncheck it I need it to remove this event handler I figured that I'd just do this (See below)

textBox1.TextChanged += (s, a) =>
            {

            };

But I want to know if there is a proper way to delete the event handler all together instead of leaving an open handler to do nothing.

1
  • 1
    Um... += just adds another handler (there can be many). You're better off making an actual method that you can readily -= when you're done with it. Commented Jun 25, 2017 at 21:15

1 Answer 1

1

You can clear the invocation list of an event form within the class, but in your case you can only unsubscribe event handlers from it.

Since you're using anonymous methods you cant do that either, you need to keep a reference of the method somewhere, later you can use the -= operator to remove it from the invocation list.

You can extract your anonymous method to a named method like this:

private void MyMethod(object sender, EventArgs args)
{
    JRPC.SetMemory(rgh, 0xc035261d, reverseBytes(textBox1.Text));
    JRPC.SetMemory(rgh, 0xc035261c, getBytes(Encoding.ASCII.GetBytes(textBox1.Text + "\0")));
}

Than you will subscribe it to the event like this:

textBox1.TextChanged += MyMethod;

If you want to remove it and no longer call it when the event is invoked:

textBox1.TextChanged -= MyMethod;
Sign up to request clarification or add additional context in comments.

3 Comments

Could you explain more on how to do that i've been looking around and found some stuff but im very confused on how remove it.
@areed99 added example of how you can do that.
Worked perfectly thank you and I better understand what I was doing wrong thanks to your examples I appreciate it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.