2

I know that this question has already been asked on How to detect my application is idle in c# (form covered)?, and on How to detect my application is idle in c#? But I couldn't find an optimal solution to my problem in those posts.

I have an application which needs to logout if a certain time has passed. We are currently using getLastInput method which tells the number of ticks from the last user input. We subtract this time from the current time, and converting this time using fromMiliseconds we check if the time passed from the last input is larger than our threshold, and if so we log out.

The problem is that the getLastInput method returns quickly and the diff doesn’t reach the threshold despite the fact no input is entered to the application.

I think that hooking into mouse/key events through windows will be slow, since every time an input occurs we will need to reset the timer.

I will be glad to hear your ideas.

adielas
  • 39
  • 3

2 Answers2

0

As far as I know, there is no way to circumvent a check on user interactions, but you could actually lighten them a little bit:

using System;
using System.Windows.Forms;

namespace MyApp
{
    [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
    public class MyForm : Form, IMessageFilter
    {
        public MyForm()
        {
            // Your code...

            InitializeComponent();

            Application.AddMessageFilter(this);
        }

        public Boolean PreFilterMessage(ref Message m)
        {
            Boolean activated = (m.Msg == 0x010) || (m.Msg == 0x0A0) || (m.Msg == 0x100) || (m.Msg == 0x101) || (m.Msg == 0x200);

            if (activated)
                // Your timer logics...

            return false;
        }
    }
}
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
0

You can use System.Timers in order to solve your issue.

System.Timers.Timer timer1 = new System.Timers.Timer();
            timer1.Interval = 1000;  //milliseconds after which you want to exit the application
            timer1.Start();
            timer1.Elapsed += TimerTick;

 private void TimerTick(object sender, ElapsedEventArgs e)
  {
    if (Win32.GetIdleTime() > 1000)
      {
         Environment.exit();
      }
  }
hustlecoder
  • 187
  • 1
  • 1
  • 9