Saravana Kumar Saravana Kumar - 1 year ago 236
C# Question

Detect windows logon attempts programmatically using C#

I want to develop a windows forms application to monitor my network computers do login, logoff and login attempts details and do something based on detection. (For example send some notification for admin)

What I have tried:

I read about windows service, Windows Task Scheduler and Event auditing using Task Scheduler But I want to do it pragmatically. So my question is How can I detect windows logon attempts programmatically using C#?

Answer Source

To detect logon attempts you can rely on windows security events. Here you can see a list of security events and their meanings. Common events which you may be interested in are:

4624: An account was successfully logged on.
4625: An account failed to log on.
4648: A logon was attempted using explicit credentials.
4675: SIDs were filtered.

Detect Events using an Application/Service

You can detect logon attempts yourself by code using EventLog class and handling its EntryWritten event. The code sample below just logs the event in a file to show you can be informed of event and use it. Instead of writing in a file, you can send notification by email or run an application or do something else.

To test the code you should Run as Administrator. Also in a real environment you should make it like a service or configure it to run before user login.

private void Form1_Load(object sender, EventArgs e)
    EventLog logListener = new EventLog("Security");
    logListener.EntryWritten += logListener_EntryWritten;
    logListener.EnableRaisingEvents = true;
void logListener_EntryWritten(object sender, EntryWrittenEventArgs e)
    //4624: An account was successfully logged on.
    //4625: An account failed to log on.
    //4648: A logon was attempted using explicit credentials.
    //4675: SIDs were filtered.
    var events = new int[] { 4624, 4625, 4648, 4675 };
    if (events.Contains(e.Entry.EventID))
        System.IO.File.AppendAllLines(@"d:\log.txt", new string[] {
            string.Format("{0}:{1}",  e.Entry.EventID, e.Entry.Message)

Note: As also you said in the question you can use Windows Scheduled Task to do something when an Event Occurred.

You can ask the Windows to do something for you when an unsuccessful logon attempt detected, for example run an application (which sends an email or somethings else). To do so, use Windows Task Scheduler and say the task run when an specific event occurred and specify suitable event source and Id. Also to see an example of complete steps see Getting event log contents by email on an event log trigger.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download