Reputation: 762
I am making a Windows Desktop Application that will run only one instance per machine. Once it gets started I need to get notified anytime a user logs in even if it was a session unlock? The SystemEvents.SessionSwitch event captures only the session switch for the user that started the application while I need to capture the events for all users.
Upvotes: 1
Views: 2495
Reputation: 3416
I think you have to use a Windows Service, which executes before a user logged in, into your system, to capture all events. After that notify your application about the changes. I use following approach.
SessionId
in SessionChangeDescription struct, from the wtsapi32
and the WTSQuerySessionInformation method.I added the basic parts of this implementation below.
public class CustomService : ServiceBase
protected override void OnSessionChange(SessionChangeDescription desc)
{
switch (desc.Reason)
{
case SessionChangeReason.SessionLogon:
var user = CustomService.UserInformation(desc.SessionId);
CustomService.DoWhatEverYouWant(user);
break;
}
}
private static User UserInformation(int sessionId)
{
IntPtr buffer;
int length;
var user = new User();
if (NativeMethods.WTSQuerySessionInformation(IntPtr.Zero, sessionId, NativeMethods.WTS_INFO_CLASS.WTSUserName, out buffer, out length) && length > 1)
{
user.Name = Marshal.PtrToStringAnsi(buffer);
NativeMethods.WTSFreeMemory(buffer);
if (NativeMethods.WTSQuerySessionInformation(IntPtr.Zero, sessionId, NativeMethods.WTS_INFO_CLASS.WTSDomainName, out buffer, out length) && length > 1)
{
user.Domain = Marshal.PtrToStringAnsi(buffer);
NativeMethods.WTSFreeMemory(buffer);
}
}
if (user.Name.Length == 0)
{
return null;
}
return user;
}
}
Upvotes: 3