How to trigger the code piece when variable changes in C#

114 Views Asked by At

I'm currently creating a simulation in C#. I am using OpenGl-TaoFramework. I ve encountered some problem . I used Glut.glutMainLoop(); function in code but I learnt that this function never returns and the program stopped. If I click the button after change variables, it works as I want but the problem is that I dont want to use button. But other way I couldnt be succeed to recall Glut.glutMainLoop(); again. Any help would be much appreciated.

   private void button1_Click(object sender, EventArgs e)
       {

           i = Convert.ToInt32(textBox1.Text);
           j = Convert.ToInt32(textBox2.Text);
           k = Convert.ToInt32(textBox3.Text);
           l = Convert.ToInt32(textBox4.Text);
           m = Convert.ToInt32(textBox5.Text);


          Glut.glutMainLoop();


        }
1

There are 1 best solutions below

0
On

If I understand your question correctly you would like to trigger a function every time that a variable changes, for this you could use an eventhandler. Here is a code example for a very basic eventhandler

public class Program
{

public delegate void ChangedEventHandler(object sender, EventArgs e);

public static void Main()
{
    var glut = new GlutVar();

    glut.Change += DoWhenEventTriggers;

    glut.GlutInt = 5;

}

public static void DoWhenEventTriggers(object sender, EventArgs e)
{
    Console.WriteLine("Event triggered");
}

private class GlutVar
{

    public event ChangedEventHandler Change;
    private int _GlutInt = 0;

    public void OnChange()
    {
        if(Change != null)
            Change(this,EventArgs.Empty);
    }

    public int GlutInt {
        get 
        {
            return _GlutInt;        
        } 
        set 
        {
            _GlutInt = value;
            OnChange();
        }
    }
}

}

DoWhenEventTriggers will run every time that the variable Glutint changes, So you could do a similar setup that will allow your code to trigger Glut.glutMainLoop(); when a variable changes.