I am working on service application that needs to monitor windows session changes and automatically start an application if a specific user logged on to.
Here is how it works, I have a file with a list of Windows usernames stored in a user principal name format (user@domain.LOCAL). My service will monitor any session changes and will take certain actions once one of those users gets logged on.
List<string> _UsersList;
object _sessionCheckLock = new object();
void OnCheckSession(int nSessionId, bool bIsLoggIn)
{
lock(_sessionCheckLock)
{
try
{
string sUserName = string.Empty;
string sDomain = string.Empty;
IntPtr pUserName = IntPtr.Zero;
uint nBytesReturned = 0;
if (WTSQuerySessionInformation(IntPtr.Zero, (uint)nSessionId, WTS_INFO_CLASS.WTSUserName, out pUserName, out nBytesReturned) && (pUserName != IntPtr.Zero))
{
sUserName = Marshal.PtrToStringAnsi(pUserName);
WTSFreeMemory(pUserName);
IntPtr pDomain = IntPtr.Zero;
if(WTSQuerySessionInformation(IntPtr.Zero, (uint)nSessionId, WTS_INFO_CLASS.WTSDomainName, out pDomain, out nBytesReturned) && (pDomain != IntPtr.Zero))
{
sDomain = Marshal.PtrToStringAnsi(pDomain);
WTSFreeMemory(pDomain);
}
else
{
}
if (!string.IsNullOrEmpty(sUserName))
{
if(!string.IsNullOrEmpty(sDomain)
{
sUserName += "@" + sDomain;
}
foreach(string username in _UsersList)
{
if(string.Compare(sUsername, username, true)==0)
{
//Do a couple of things
return;
}
}
}
}
else
{
return;
}
}
catch (System.Exception ex)
{
}
}
}
The above code is the function I call whenever a new logon event is raised. The _UsersList is a list of strings that contains all the usernames that the service is allowed to work with.
The problem here is that WTSQuerySessionInformation when used with WTS_INFO_CLASS.WTSDomainName does not return the full name of the domain and therefore the comparison fails.For example if a username called (username@DOMAIN.LOCAL) exists in the list of user and logs on, when querying for the domain name of the session, it returns only (DOMAIN) without the .LOCAL appendix. I need to find a way to get the full domain name to match the one in my list.
Can someone help please
Look into Cassia.Net, this is a very useful.
You can download the source code, i used this for a project where i had to get all the users that were logged on to a server.
cassia
.NET Windows Terminal Services / Remote Desktop Services Library
http://code.google.com/p/cassia/
hope that helps