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.

Avery
  • 3
  • 2
  • 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. – Clay Jun 25 '17 at 21:15

1 Answers1

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;
Deadzone
  • 793
  • 1
  • 11
  • 33
  • 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. – Avery Jun 25 '17 at 23:02
  • @areed99 added example of how you can do that. – Deadzone Jun 25 '17 at 23:10
  • 1
    Worked perfectly thank you and I better understand what I was doing wrong thanks to your examples I appreciate it! – Avery Jun 25 '17 at 23:43