Shoot event only once

Asked

Viewed 268 times

8

I’m doing an interface in Visual Studio 2015, how do I hold an event just once?

For example:

private void textBox5_Click(object sender, EventArgs e)
{  
    textBox5.ForeColor = Color.Black;
    textBox5.SelectAll();
    textBox5.Text = "";        
}

When the user clicks on the text box, the color changes to black, and then selects everything and clears.

But I want this to happen only once, that is, if the user clicks again do not do any action.

  • You can also ask the color. If it is Forecolor == Color.Black does nothing.

  • 1

    It would work, but it would be a gambiarra kkkkk The same is how the response people sent (textBox5.Click -= textBox5_Click;)

2 answers

11


Untie the component event.

Thus, whenever the form is "built" the event will be linked to the component and, when it is first fired, will be unlinked.

Maybe it’s not the best way to do it, but without more details it’s hard to think of a better way.

private void textBox5_Click(object sender, EventArgs e)
{  
    textBox5.ForeColor = Color.Black;
    textBox5.SelectAll();
    textBox5.Text = "";

    textBox5.Click -= textBox5_Click;
}
  • That’s right, it worked!! Thank you

7

It’s very simple. I can’t give many details because I haven’t seen the whole code, but in essence just sign up for the event. If this object can register, it can do the opposite:

private void textBox5_Click(object sender, EventArgs e) {  
    textBox5.ForeColor = Color.Black;
    textBox5.SelectAll();
    textBox5.Text = "";
    textBox5.Click -= textBox5_Click; //provavelmente isto
}

I put in the Github for future reference.

  • That’s right, it worked!! Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.