visual c# - 从Windows服务通知当前用户的最简单方法是什么

时间:2016-07-27 20:07:14

标签: c# visual-studio service alert

我需要从Windows服务提醒当前用户。 我在互联网上看到了一些复杂的方法,但大多数都是过时的。 我希望Windows 10能有一些简单的东西。 我正在尝试的一个想法是创建一个包含简单消息的WPF应用程序......

System.Diagnostics.Process.Start("C:\\blah\\WpfApplication1.exe");

...但它在后台运行,因为该服务不知道要运行它的用户。 所以我需要获取当前登录的桌面用户(如果有多个用户,那么我将通知所有用户)。然后,如果我能以某种方式使用CreateProcessAsUser或类似的东西,那就可以了。 提前谢谢,

2 个答案:

答案 0 :(得分:0)

Windows服务在称为System的高级状态下运行,该状态由Microsoft设计为不与用户交互。但是,有一种方法可以使用Microsoft编写here的命名空间从服务启动应用程序。

在代码中包含命名空间并执行它 CreateProcessAsUserWrapper.LaunchChildProcess(PATH_TO_EXE)

有关于此的stackoverflow答案:

答案 1 :(得分:0)

User Pixel回答了我的问题,但我想为未来的搜索者提供更多详细信息。代码在http://www.getcodesamples.com/src/FBB7577C/7A33AB93处可用,但如果它消失,则只搜索CreateProcessAsUserWrapper。将代码粘贴到Service1.cs工作空间中,并删除顶部命名空间行和相应的括号,因为您已有一个命名空间。所以第一行将是:

class CreateProcessAsUserWrapper

此外,将它放在您的服务类之后,它必须是第一类。我没有添加任何使用语句,因此我不知道它使用哪些语句。我将粘贴下面使用的所有内容。

using Microsoft.Win32; // for registry key
using System;
using System.Collections; // for getfiles
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics; // for log writing
using System.IO; // for file watcher, file i/o, directory.exists
using System.Linq;
using System.Net;
using System.Runtime.InteropServices; // for SHGetKnownFolderPath
using System.Security.Permissions; // for file watcher, registry key
using System.ServiceProcess;
using System.Text;
using System.Threading; // for sleep
using System.Timers; // for timers

然后,正如Pixel所提到的,你所要做的就是从你的服务中调用它,如:

CreateProcessAsUserWrapper.LaunchChildProcess("C:\\blah\\WpfApplication1.exe")