【问题标题】:how to use WtsApi32.dll in lock/Unlock session handler in windows service?如何在 Windows 服务的锁定/解锁会话处理程序中使用 WtsApi32.dll?
【发布时间】: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


【解决方案1】:

MSDN:

SystemEvents.SessionSwitch Event:

仅当消息泵正在运行时才会引发此事件。在 Windows 服务中,除非使用隐藏表单或手动启动消息泵,否则不会引发此事件。有关显示如何在 Windows 服务中使用隐藏表单来处理系统事件的代码示例,请参阅 SystemEvents 类。

代码示例在this page,其中还注明:

服务没有消息循环,除非它们被允许与桌面交互。如果消息循环不是由隐藏表单提供的,如本例,服务必须在本地系统帐户下运行,并且需要手动干预才能与桌面交互。也就是说,管理员必须手动选中服务属性对话框的登录选项卡上的允许服务与桌面交互复选框。在这种情况下,会自动提供消息循环。仅当服务在本地系统帐户下运行时,此选项才可用。无法以编程方式启用与桌面的交互。

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    相关资源
    最近更新 更多