Search This Blog

Sunday, September 6, 2009

How to get a session state change notification in Windows-(Win32)

Intro.

Every Windows users must be familiar with the term session. Generally, a session in windows is the time between Windows is booted to the time of Shutdown. The session has some states which can get changed dynamically while Windows runs. These state changes include User Logoff, User Logons, Lockdown and Unlock of users, Remote logon and logoff etc. We have nothing to do with these session states, but there are certain situations in which we may need to catchup these session state change and prepare our application to do certain tasks accordingly.

How to do.


The Windows Terminal Service helps us to recognize and get notified about session state change windows messages. The session state message is sent only to applications that have registered to receive this message by calling WTS API WTSRegisterSessionNotification(). After registered, the application starts to get notified of session state change windows messages. We can process these messages to get session events such as User Logon, Logoff, Lockdown and Unlock etc.


Code.


First of all, add this line of code in the WM_CREATE message handling section of your Application Window. If your application does not have a Window, add this in your main().


WTSRegisterSessionNotification( hWnd, NOTIFY_FOR_ALL_SESSIONS ) ;


Now our program begins getting WM_WTSSESSION_CHANGE message from Windows Terminal Service whenever a session event occurs. Next step is very simple. We just need to catch up the session state messages from wParam of this message, and handle them acordingly.


Add this block of code in your Message Handler. :-


case WM_WTSSESSION_CHANGE:

  wmSessionStat = LOWORD(wParam);
  switch( wmSessionStat )
   {
     case WTS_SESSION_LOCK:
     //The session is getting locked.
     break;
     case WTS_SESSION_UNLOCK:
     //A session is unlocked.
     break;
     case WTS_SESSION_LOGON:
     //A User logged in.
     break;
     case WTS_SESSION_LOGOFF:
     //A user is logging out.
     break;
     case WTS_REMOTE_CONNECT:
     //A session connected remotely.
     break;
     case WTS_REMOTE_DISCONNECT:
     //A session is getting disconnected remotely.
     break;
   }
break;


I hope i explained well. Rest is the work of MSDN and You. 8-)

Comments and Feedbacks expected :-)

1 comment: