namespace MonitorService
{
public partial class MonitorSv : ServiceBase
{
string AppName = "",MusicName = "";
string apppath = "";
Thread threadwork;
SoundPlayer player;
public MonitorSv()
{
InitializeComponent();
string path = Directory.GetCurrentDirectory()+"\\Resources\\XML\\AppFile.xml";// Directory.GetCurrentDirectory() + "\\Resources\\XML\\AppFile.xml";
string[] names = RwXmlBs.ReadXml(path);
if (names != null && names.Length == )
this.AppName = names[];
this.MusicName = names[];
//Beep(1000, 10000);//调试可以响,但是安装后不响,所以改成播放声音 //WriteFile(names[0] + "<=>" + names[1] + "++path:" + path, 0, "构造函数");
PlayMusic(); } private void PlayMusic()
{
if (String.IsNullOrEmpty(MusicName))
return;
player = new SoundPlayer();
player.SoundLocation = @"D:\\spring.wav";// MusicName;// @""+ MusicName + "";
player.Load(); //同步加载声音
player.Play(); //启用新线程播放
} private void PlayerStop()
{
if (player != null)
{
player.Stop();
}
}
protected override void OnStart(string[] args)
{
if (threadwork == null)
{
threadwork = new Thread(CheckAppMethod);
threadwork.IsBackground = true;
threadwork.Start();
}
} private void CheckAppMethod()
{
Process[] ps = null;
try
{
while (true)
{
if (!String.IsNullOrEmpty(AppName))
{
ps = Process.GetProcessesByName(AppName); // "MakeCard"); //不用带.exe
if (ps.Length <= )//进程被杀死,则报警.
{
PlayMusic();
//Been(500,1000);//不可以响,搞不懂
}
else
{
PlayerStop();
}
}
System.Threading.Thread.Sleep();
}
}
catch (Exception EX)
{
WriteFile(AppName, ps.Length, "异常的"+EX.ToString());
OnShutdown();
}
} private void WriteFile(string AppName,int Length, string EX)
{
try
{
FileStream fs = new FileStream(apppath+"\\CloseFileLog.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(, SeekOrigin.End);
sw.WriteLine("AppName:" + AppName + "++ps.Length:" + Length + ">>>" + DateTime.Now.ToString() + EX.ToString() + "\n");
sw.Flush();
sw.Close();
fs.Close();
}
catch (Exception ex)
{ }
} protected override void OnShutdown()
{
base.OnShutdown();
} protected override void OnStop()
{
GC.Collect();
PlayerStop();
} // 第一个参数是指频率的高低,越大越高,第二个参数是指响的时间多长
[DllImport("kernel32.dll", EntryPoint = "Beep")]
public static extern int Beep(int dwFreq,int dwDuration);
}
}