【发布时间】:2012-11-15 10:19:03
【问题描述】:
我想使用 Windows 服务检测并关闭任何程序(例如:Notepad.exe)。下面的代码在控制台应用程序中是不错的选择。
class Program
{
private static SessionSwitchEventHandler sseh;
static void Main(string[] args)
{
sseh = new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
SystemEvents.SessionSwitch += sseh;
while (true) { }
}
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
Console.WriteLine(e.Reason.ToString());
}
}
但上面的代码在 windows 服务 windows 7 中不起作用。看这个链接:
http://social.msdn.microsoft.com/Forums/eu/netfxcompact/thread/04b16fac-043a-41c3-add9-482c912e95be
我在 windows 服务中编写了以下代码,它不能在 win 7 上运行,它每次都在控制台应用程序中的 windows 7 上运行。
protected override void OnStart(string[] args)
{
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
Console.ReadLine();
SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
}
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
WriteToLogFile( e.Reason.ToString());
if (e.Reason == SessionSwitchReason.SessionLock)
{
WriteToLogFile("SessionLock ");
}
if (e.Reason == SessionSwitchReason.SessionUnlock)
{
WriteToLogFile("SessionUnlock ");
}
if (e.Reason == SessionSwitchReason.SessionLogon)
{
WriteToLogFile("SessionLogon ");
}
}
我已经阅读了这篇文章(http://rhauert.wordpress.com/category/ucc/)但我不能使用
protected override void OnStart(string[] args)
{
WriteToText("Windows Service is started");
SessionChangeHandler x = new SessionChangeHandler();
}
【问题讨论】:
-
你只说“不工作”和“不能使用”。如果您想要更好的答案,请提供有关具体情况、您期望发生的情况以及您尝试过的情况的信息。
标签: c# .net visual-studio-2010 wmi interopservices