Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive event when network is connected and also when user logs in

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)

like image 318
Rory Avatar asked Mar 26 '09 19:03

Rory


2 Answers

//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
        }
    }
}
like image 170
Timothy Carter Avatar answered Oct 12 '22 23:10

Timothy Carter


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); 
like image 31
SLaks Avatar answered Oct 13 '22 00:10

SLaks