+2 votes
229 views
i have to develop an application using windows forms.when its idle for more than 10 mins at any form, i want to log off from application and again ask user name and password to access..thank you
asked May 23, 2016 in Computer Science - IT by gypsiii
edited May 23, 2016 by slow_learner | 229 views
Good question ! +1 .. You need to start a timer once form is loaded..when time reaches more than 10mins..show login window..But make sure that 10mins restarts if some user action is made...

1 Answer

+2 votes
Selected Ans.

First Add namespace : 

using System.Runtime.InteropServices;

Add a timer to your Form 

Add Below Functions to your Form code

Get Last Input Time :

 public static long GetLastInputTime()
        {
            LASTINPUTINFO LastUserAction = new LASTINPUTINFO();
            LastUserAction.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(LastUserAction);
            if (!GetLastInputInfo(ref LastUserAction))
            {
                throw new Exception(GetLastError().ToString());
            }

            return LastUserAction.dwTime;
        }

Get Idle Time :

        public static uint GetIdleTime()
        {
            LASTINPUTINFO LastUserAction = new LASTINPUTINFO();
            LastUserAction.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(LastUserAction);
            GetLastInputInfo(ref LastUserAction);
            return ((uint)Environment.TickCount - LastUserAction.dwTime);
        }

Add code to import dll :

        [DllImport("User32.dll")]
        private static extern bool GetLastInputInfo(ref LASTINPUTINFO Dummy);
        [DllImport("Kernel32.dll")]
        private static extern uint GetLastError();

Declare a struct as below :        

      internal struct LASTINPUTINFO
        {
            public uint cbSize;
            public uint dwTime;
        }

Add timer code as below :

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (GetIdleTime() > 10000)  //10 secs, Time to wait before locking
                this.Close(); // Replace this line with code to show Login Form
        }

Make sure to start timer at form load :

        private void Form1_Load(object sender, EventArgs e)
        {

            timer1.Start();
        }

More Reference :

Ref1,Ref2,Ref3

answered May 23, 2016 by slow_learner
selected May 24, 2016 by gypsiii
not working..
those codes are tried and tested ..post your efforts / error messages and more clarity on whats not working
i have forgotten to start the timer at load ..please have a check now
yes working...tanq fast learner..
welcome gypsiii :)