1

I have a simple service with the following code:

on Program.Main method I have the code which is generated by vs itself(2010):

static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new Service1() 
        };
        ServiceBase.Run(ServicesToRun);
    }

And in Service1.cs I have:

 protected override void OnStart(string[] args)
    {
        System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer(@"C:\doorbell-1.wav");
        myPlayer.Play();
    }

    protected override void OnStop()
    {
    }

I have omit writing the usual automatically generated c# codes to reduce the complexity.

Logically a sound should be played when I start the service but nothing happens when I start the service. Please note that:

1-I install the service using installUtill.exe. 2-The service runs under the localSystem account privilege. 3-Duration of the mentioned .wav file is 3Seconds.

How can I play that sound? Thanks in advance.

4

3 回答 3

2

简单的答案是你不能。Windows 服务不与桌面交互,因此它们无法使用音频服务等桌面功能。

请记住,Windows 是一个多用户操作系统。你能想象如果 5 个同时登录的用户开始播放音频会发生什么吗?

所有用户都有一个所谓的“Windows Station”,并且有一个特殊的 Windows Station 供登录到物理计算机的用户使用。Windows 服务有一个空的或唯一的(非交互的)Windows Station,因此不能与控制台 WS 交互。

此 Windows Station 用于重定向音频,控制台 WS 中的音频会发送到扬声器。所有其他音频要么被重定向到他们正在使用的网络站,要么什么都不做。

一个更复杂的答案是它可能是可能的,因为 Windows 音频服务本身就是另一个服务,您可能可以直接与它交互,但这将是非常低级的,并且您可能不够熟练。

最后,可以使服务与桌面交互。但是,这被认为是不推荐使用的功能,并不总是易于使用。这也是一个巨大的安全漏洞,使您的服务容易被恶意软件用来破坏机器。

于 2014-03-16T21:00:47.080 回答
0

昨晚我一直在整个互联网上搜索。这个问题已经被回答了很多次,但从来没有一个简单的答案。如果你有同样的问题,当服务要求它时,有一种非常简单但很棘手的方法来做某事。

假设您想在服务启动时播放一首歌曲。

首先创建一个 EventLog 类:

public class EventLogEngine
{
    private string _sourceName, _logName;
    public EventLogEngine(string sourceName, string logName)
    {
        if (!EventLog.SourceExists(sourceName))
            EventLog.CreateEventSource(sourceName, logName);
        _sourceName = sourceName; _logName = logName;
    }
    public void WriteLog(string message, EventLogEntryType eventType, int Id)
    {
        EventLog.WriteEntry(_sourceName, message, eventType, Id);
    }
}

protected override void OnStart(string[] args)
{
 EventLogEngine eventWriter = new EventLogEngine("mySource","myLog");
eventWriter.WriteLog("sourceName","Service started",EventLogEntryType.Information,"anyId");
}

到这里为止没有任何关于播放声音的事情,也没有什么复杂的。但是如何播放声音或做其他事情呢?这是答案:)

1-转到控制面板并打开事件查看器

2-找到您的事件日志并单击它

在此处输入图像描述

3-在右侧面板上,您将看到您通过代码编写的条目。

4-右键单击条目并选择将任务附加到此事件!

在此处输入图像描述

到目前为止,你应该已经明白我要做什么了。正确的?

5-选择该选项并声明设置此条目时要执行的操作。您可以简单地附加任意数量的任务。

在此处输入图像描述

现在编写一个播放声音的程序(例如:在 vb6 中)并告诉事件查看器在每次写入此条目时执行此程序(每次您的服务启动时)

于 2014-03-17T09:13:14.227 回答
0

可以Windows 服务播放声音。

从 Windows 服务播放波形文件 (C#)

从服务播放声音不会违反交互规则,因为它不是交互功能:它是一个通知。

于 2016-04-06T02:17:49.507 回答