Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if event comes from user input in C#?

I have a small form with some check boxes on it, and there's a message handler for each of the check boxes for the CheckChanged event. Since some of the check boxes are dependent on others, if one check box's checked state changes, it changes the checked state of any dependent check boxes. I've found that this causes the events to be raised on the other check boxes, but my issue is that each of the events has one function call that should only be called if the event came from the user actually clicking on the check box. I'd like to know how to tell (presumably from either sender or the EventArgs) if the CheckChanged event was caused by a mouse click or not.

Cliffs:

  • Multiple check boxes receiving CheckChanged event
  • Need to determine if event was raised by a mouse click or not
like image 650
riqitang Avatar asked Mar 21 '13 14:03

riqitang


1 Answers

You can use a flag to indicate whether or not to ignore events. Its probably easier than unsubscribing from the event handlers. Its not very sophisticated but it should do the job.

I put together a quick example:

   bool ignoreEvents = false;
        public Form1()
        {
            InitializeComponent();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            ignoreEvents = true;
            checkBox2.Checked = checkBox1.Checked ;
            checkBox3.Checked = checkBox1.Checked;
            ignoreEvents = false;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (ignoreEvents) return;
            MessageBox.Show("Changed in 2");
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (ignoreEvents) return;
            MessageBox.Show("Changed in 3");
        }
like image 98
Alex Avatar answered Sep 25 '22 03:09

Alex