Home > Net >  How to make the event wait until a boolean is changed
How to make the event wait until a boolean is changed

Time:08-17

I have an event registered.

layout.SizeChanged  = parentToggleBox.Resize;

Problem is, I would like this Resize event to wait until my mouse has moved away from the box.

How to make this event wait until a boolean is changed from false to true? or wait until OnMouseLeave(object sender, MouseEventArgs e) is triggered?

CodePudding user response:

Here's an example that I put together:

public class Form1 : Form
{
    private Panel Panel1;
    private Label Label1;

    public Form1()
    {
        this.Panel1 = new Panel()
        {
            BackColor = System.Drawing.Color.Red,
        };

        this.Label1 = new Label()
        {
            Top = 200,
            Text = "Click",
        };

        bool clicked = false;
        bool entered = false;

        this.Panel1.Click  = (s, e) =>
        {
            this.Panel1.BackColor = System.Drawing.Color.Blue;
            clicked = true;
        };

        this.Panel1.MouseEnter  = (s, e) =>
        {
            this.Panel1.BackColor = System.Drawing.Color.Yellow;
            clicked = false;
            entered = true;
        };

        this.Panel1.MouseLeave  = (s, e) =>
        {
            if (entered && clicked)
            {
                this.Panel1.BackColor = System.Drawing.Color.Green;
                this.Label1.Text = "Success";
            }
        };

        this.Controls.Add(this.Panel1);
        this.Controls.Add(this.Label1);
    }
}

I've used a Click event rather than a Resize to demonstrate the technique.

Effectively this is just setting two booleans and when the right combination of entered and clicked occurs then the code in the block that contains this.Label1.Text = "Success"; will run.

The colours are set for debugging purposes.

To run, do this:

var form1 = new Form1();
form1.ShowDialog();
  • Related