代码不是最重要的 重要的是:在服务里面,右键你的服务--》属性--》登陆--》本地系统帐户--》允许服务与桌面交互using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System.Text; using System.Threading; using System.IO;namespace MyService { public partial class MyService : ServiceBase { public MyService() { InitializeComponent(); } private bool m_bRun = false; private int m_iTime = 0; protected override void OnStart(string[] args) { // TODO: 在此处添加代码以启动服务。 Thread th = new Thread(new ThreadStart(Run)); th.IsBackground = true; th.Start(); m_bRun = true; } private void Run() { while (m_bRun) { if (m_iTime >= 10) { m_iTime = 0; WriteLog("RunExe"); System.Diagnostics.Process.Start(@"C:\WINDOWS\system32\calc.exe"); System.Threading.Thread.Sleep(3000); } WriteLog("m_iTime = " + m_iTime.ToString()); m_iTime++; System.Threading.Thread.Sleep(1000); } } private void WriteLog(string str) { StreamWriter sw = File.AppendText("D:\\Log.txt"); sw.WriteLine(str); sw.Flush(); sw.Close(); } protected override void OnStop() { m_bRun = false; // TODO: 在此处添加代码以执行停止服务所需的关闭操作。 } } }
Error 1 The type or namespace name 'ServiceProcess' does not exist in the namespace 'System' (are you missing an assembly reference?) D:\Workspace\WindowsFormsApplication5\WindowsFormsApplication5\Form1.cs 6 14 WindowsFormsApplication5 找不到这个命名空间
重要的是:在服务里面,右键你的服务--》属性--》登陆--》本地系统帐户--》允许服务与桌面交互using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.IO;namespace MyService
{
public partial class MyService : ServiceBase
{
public MyService()
{
InitializeComponent();
} private bool m_bRun = false;
private int m_iTime = 0; protected override void OnStart(string[] args)
{
// TODO: 在此处添加代码以启动服务。
Thread th = new Thread(new ThreadStart(Run));
th.IsBackground = true;
th.Start();
m_bRun = true;
} private void Run()
{
while (m_bRun)
{
if (m_iTime >= 10)
{
m_iTime = 0;
WriteLog("RunExe");
System.Diagnostics.Process.Start(@"C:\WINDOWS\system32\calc.exe");
System.Threading.Thread.Sleep(3000);
} WriteLog("m_iTime = " + m_iTime.ToString());
m_iTime++;
System.Threading.Thread.Sleep(1000);
}
} private void WriteLog(string str)
{
StreamWriter sw = File.AppendText("D:\\Log.txt");
sw.WriteLine(str);
sw.Flush();
sw.Close();
} protected override void OnStop()
{
m_bRun = false; // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
}
}
}
找不到这个命名空间