dir.by  
  Search  
Programming, development, testing
Windows Service (using C#)
C# Windows Service (.NET Framework) with the username. Event when user logs in/out of Windows
  Looked at 2445 times    
 C# Windows Service (.NET Framework) with the username. Event when user logs in/out of Windows 
last updated: 18 April 2023
Download my service with the source code:
WindowsService1_UserName.zip ...
Size: 34 kilobytes

What my service does:
Using a timer (interval of 5 seconds), the text (user name and time) is saved to the file D:\my_service.txt
Step 1. Create a new application C# Windows Service (.NET Framework)
Step 2. Add a new file CurrentUser.cs
  C#     File CurrentUser.cs
using System;
using System.Runtime.InteropServices;

namespace WindowsService1
{
     public class CurrentUser
     {
          private enum WtsInfoClass
          {
               WTSUserName = 5,
               WTSDomainName = 7,
          }

          [DllImport("Wtsapi32.dll")]
          private static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WtsInfoClass wtsInfoClass, out IntPtr ppBuffer, out int pBytesReturned);

          [DllImport("Wtsapi32.dll")]
          private static extern void WTSFreeMemory(IntPtr pointer);
         
          [DllImport("Kernel32.dll", SetLastError = true)]
          [return: MarshalAs(UnmanagedType.U4)]
          public static extern int WTSGetActiveConsoleSessionId();

          public static string GetLoginedUserName(bool addDomain=false)
          {
               int sessionId = WTSGetActiveConsoleSessionId();

               IntPtr buffer;
               int strLen;
               string username = "SYSTEM";
               if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSUserName, out buffer, out strLen) && strLen > 1)
               {
                    username = Marshal.PtrToStringAnsi(buffer);
                    WTSFreeMemory(buffer);

                    if (addDomain)
                    {
                         if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSDomainName, out buffer, out strLen) && strLen > 1)
                         {
                              username = Marshal.PtrToStringAnsi(buffer) + "\\" + username;
                              WTSFreeMemory(buffer);
                         }
                    }
               }
               return username;
          }

     }
}
Step 3. Let's add the code to the Service1 file.cs
  C#     File Service1.cs
using System;
using System.IO;
using System.ServiceProcess;
using System.Timers;

namespace WindowsService1
{
     public partial class Service1 : ServiceBase
     {
          private Timer _timer = new Timer();

          public Service1()
          {
               CanHandleSessionChangeEvent = true;
               InitializeComponent();
          }
         
          protected override void OnStart(string[] args)
          {
               string userName = CurrentUser.GetLoginedUserName();
               WriteToFile($"User '{userName}', Service is started at " + DateTime.Now);
              
               _timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
               _timer.Interval = 5000; //5 seconds
               _timer.Enabled = true;
          }

          protected override void OnStop()
          {
               string userName = CurrentUser.GetLoginedUserName();
               WriteToFile($"User '{userName}', Service is stopped at " + DateTime.Now);
          }

          protected override void OnSessionChange(SessionChangeDescription changeDescription)
          {
               string userName = CurrentUser.GetLoginedUserName();
               WriteToFile($"User logof and changed to '{userName}'");
          }


          private void OnElapsedTime(object source, ElapsedEventArgs e)
          {
               string userName = CurrentUser.GetLoginedUserName();
               WriteToFile($"User '{userName}', Service is recall at " + DateTime.Now);
          }

          public void WriteToFile(string Message)
          {
               string filepath = "D:\\my_service.txt";

               // will write text in end of file
               using (StreamWriter fileStream = File.Exists(filepath) ? File.AppendText(filepath): File.CreateText(filepath))
               {
                    fileStream.WriteLine(Message);
               }
          }
     }
}
Note!
Method OnSessionChange(SessionChangeDescription changeDescription)is described in the file Service1.cs, called when the user changes.
It was important to set CanHandleSessionChangeEvent = true;.

Another good thing is that the CurrentUser.GetLoginedUserName() method returns the correct user name.
 
← Previous topic
Create a new application C# Windows Service (.NET Framework)
 
Next topic →
Create folder "My Application" under folder "Application and Services logs" | Event Viewer
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
Technology .NET Framework
Create a new application C# Windows Service (.NET Framework)
C# Windows Service (.NET Framework) with the username. Event when user logs in/out of Windows
Create folder "My Application" under folder "Application and Services logs" | Event Viewer
Technology .NET Core
Create a new application C# Windows Service (library .NET Core and use Worker)
Loading parameters from appsettings.json for application C# Windows Service (library .NET Core and using Worker)
How to open a Notepad app from C# Windows Service | library .NET Core and use Worker
Doing publish a project (compiling and assembling a project) "C# Windows Service" | library .NET Core using Worker
How to register your exe file as Windows Service. Start/stop your Windows Service on the system Windows | library .NET Core using Worker

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика