using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
// 定義變量存儲最新登錄信息
string latestLoginUser = string.Empty;
DateTime latestLoginTime = DateTime.MinValue;
try
{
// 打開指定的事件日志
EventLog eventLog = new EventLog("Microsoft - Windows - TerminalServices - LocalSessionManager/Operational", ".");
// 遍歷事件日志中的條目
foreach (EventLogEntry entry in eventLog.Entries)
{
// 事件ID為1149表示遠程連接成功事件
if (entry.EventID == 1149 && entry.EntryType == EventLogEntryType.Information)
{
// 獲取事件發生時間
DateTime entryTime = entry.TimeGenerated;
// 如果該事件時間比已記錄的最新登錄時間晚,則更新最新登錄信息
if (entryTime > latestLoginTime)
{
latestLoginTime = entryTime;
// 解析用戶信息,這里簡單地從消息中提取用戶名
// 不同系統的事件消息格式可能略有不同,需根據實際情況調整解析邏輯
string message = entry.Message;
int startIndex = message.IndexOf("user name: ") + "user name: ".Length;
int endIndex = message.IndexOf(Environment.NewLine, startIndex);
if (startIndex > 0 && endIndex > startIndex)
{
latestLoginUser = message.Substring(startIndex, endIndex - startIndex).Trim();
}
}
}
}
// 輸出最新登錄信息
if (!string.IsNullOrEmpty(latestLoginUser))
{
Console.WriteLine($"最新的遠程桌面登錄信息:");
Console.WriteLine($"登錄用戶:{latestLoginUser}");
Console.WriteLine($"登錄時間:{latestLoginTime}");
}
else
{
Console.WriteLine("未找到遠程桌面登錄信息。");
}
}
catch (Exception ex)
{
Console.WriteLine($"發生錯誤:{ex.Message}");
}
}
}