![](/img/trans.png)
[英]How can c# service identify current user logon name on Terminal Services Server?
[英]how to identify logon event in window service
我有一个Windows服务,可获取用户详细信息并将结果保存到日志文本文件中。 而且,我的问题是当我注销系统并再次登录时,即不重新启动机器..,我也想节省我将系统登录到该日志文件中的时间。如何在窗口服务中写入登录事件..请帮助发表评论
我使用了以下代码,但登录时未将任何内容写入日志文本文件。 即LogOn no-1或LogOn no-2 ...是否有任何错误或登录没有足够的时间来执行该过程。
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
StreamWriter str = new StreamWriter("D:\\Log.txt", true);
str.WriteLine("LogOn no-1: " + DateTime.Now.ToString());
str.Close();
if (e.Reason == SessionSwitchReason.SessionLogon)
{
StreamWriter str1 = new StreamWriter("D:\\Log.txt", true);
str1.WriteLine("LogOn no-2: " + DateTime.Now.ToString());
str1.Close();
}
}
http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onsessionchange.aspx
这可能是最好的选择,因为Vista和Win7就像终端服务器一样处理用户会话。 如果您需要会话ID或会话更改的原因(登录/注销/锁定等),这应该可以让您处理会话更改,并提供具有相关信息的结构。
看一下SystemEvents
类, 这是MSDN链接 。
与您的情况相关的是暴露的事件SessionEnded
, SessionEnding
和SessionSwitch
以及潜在的PowerModeChanged
。
一个简单的示例可能如下所示:
SystemEvents.SessionSwitch += OnSessionSwitch;
void OnSessionSwitch(object sender, SessionSwitchEventArgs e)
{
//implement your logic here
}
除非提供消息循环,否则不会引发这些事件。 通过添加隐藏的表单手动添加(或可能允许服务与桌面交互-不确定永远不会累,可能不建议这样做)。
我遇到一个类似的问题,其中一项服务未收到TimeZone更改,因此必须向该服务添加隐藏表单。
这是有关如何解决此问题的示例之一。
以下是我为解决问题所做的工作:
将TimeZoneForm添加到service.sln;
然后在服务的OnStart中添加以下代码: new System.Threading.Thread(RunMessagePump).Start();
并将此方法添加到服务文件:
private void RunMessagePump()
{
Application.Run(new TimeZoneForm.TimeZoneForm());
}
internal class TimeZoneForm : Form
{
public TimeZoneForm()
{
InitializeComponent();
}
private void TimeZoneForm_Load(object sender, EventArgs e)
{
SystemEvents.TimeChanged += SystemEvents_TimeChanged;
}
private void TimeZoneForm_Closing(object sender, FormClosingEventArgs e)
{
SystemEvents.TimeChanged -= SystemEvents_TimeChanged;
}
private void SystemEvents_TimeChanged(object sender, EventArgs e)
{
System.Globalization.CultureInfo.CurrentCulture.ClearCachedData();
}
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.SuspendLayout();
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(0, 0);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "TimeZoneForm";
this.Text = "TimeZoneForm";
this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
this.Load += this.TimeZoneForm_Load;
this.FormClosing += this.TimeZoneForm_Closing;
this.ResumeLayout(false);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.