Скачать мой сервис с исходным кодом:
WindowsService1_UserName.zip ...
размер: 34 килобайта
Что делает мой сервис:
Используя таймер (интервал 5 секунд) сохраняется текст(имя пользователя и время) в файл
D:\my_service.txt
C#
Файл 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;
}
}
}
C#
Файл 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);
}
}
}
}