-3

I am designing a small application in which I open a new form with some controls. I want to close this form if idle for some time. Let say the form is having many buttons, scroll bars, picture box....if none of them is clicked (within 10 seconds) the form should close.

I have used a timer of 10 seconds , i want to reset it if any of the control is pressed. I can do it individually but would become very cumbersome doing it for all the controls. Can i do it by some simpler way....I read on net:

foreach (Control cc in Controls)

but didn't knew how to use it. Please help.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Amit Garg
  • 15
  • 1

3 Answers3

0

This should get you started

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach(Control control in this.Controls)
        {
            control.Click += Oncontrol_Click;
        }
    }

    private void Oncontrol_Click(object sender, EventArgs e)
    {
        Control control = sender as Control;
        MessageBox.Show($"{control.Text} is clicked");
    }
Pepernoot
  • 3,409
  • 3
  • 21
  • 46
0

You can bind the click event to all the controls inside the foreach loop.

foreach (Control c in Controls)
{
    c.Click += (o, args) => ResetTimer();
}

Now each time a user clicks a control, ResetTimer() gets fired.

abdul
  • 1,562
  • 1
  • 17
  • 22
0

You need to do this to add the click event to all of the controls on a form:

    private void Form1_Load(object sender, EventArgs e)
    {
        AttachHandler(this, (s, e2) => ResetTimer());
    }

    private void AttachHandler(Control control, EventHandler handler)
    {
        control.Click += handler;
        foreach (Control c in control.Controls)
        {
            AttachHandler(c, handler);
        }
    }

It needs to recursively go down all controls that can contain other controls.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • Thanks for your reply. The solution was helpful but if there are some controls inside a panel on the form, they don't reflect, should they be handled seperately – Amit Garg Dec 15 '16 at 11:22
  • @AmitGarg - What do you mean they "don't reflect"? This code should attach the handler for the controls on panels too. – Enigmativity Dec 15 '16 at 22:14
  • Sorry for confusion. The code is working properly for buttons , but is not working for scroll bars (horizontal scroll bar / vertical scroll bar / textbox scroll bar ). Can you please advise – Amit Garg Dec 16 '16 at 04:18
  • @AmitGarg - Scroll bars don't respond to clicks because they are there to scroll. You'll need to expand your code to handle scrolling controls and the scrolling events. – Enigmativity Dec 16 '16 at 09:51