I have a service that runs and I'd like to receive notification when:
a) the network is connected.
b) when a user logs in to the machine.
How can I do this? (C# .NET 2.0)
//using Microsoft.Win32;
//using System.Net.NetworkInformation;
public class SessionChanges
{
public SessionChanges()
{
NetworkChange.NetworkAvailabilityChanged +=
new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
}
void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLogon)
{
//user logged in
}
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
if (e.IsAvailable)
{
//a network is available
}
}
}
To be notified when any user logs in to the machine, call WTSRegisterSessionNotification
, passing NOTIFY_FOR_ALL_SESSIONS
, and listen for the WM_WTSSESSION_CHANGE
message in the message loop.
In the message, cast the wParam
to the Microsoft.Win32.SessionSwitchReason
enum to find out what happened, and pass the lParam
to WTSQuerySessionInformation
to find the username.
[DllImport("Wtsapi32.dll", CharSet=.CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WTSRegisterSessionNotification(IntPtr hWnd, int dwFlags);
//Pass this value in dwFlags
public const int NOTIFY_FOR_ALL_SESSIONS = 0x1;
//Listen for this message
public const int WM_WTSSESSION_CHANGE = 0x02B1;
//Call this method before exiting your program
[DllImport("Wtsapi32.dll", CharSet=.CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WTSUnRegisterSessionNotification(IntPtr hWnd);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With