一个简单的windows services demo(c#)

功能:

每三十分钟扫描进程,如果不存在进程fromdemo.exe.则启动该应用程序.

1.检测进程进否存在

 

代码
 
   
/// <summary>
/// 检查进程是否已启动
/// </summary>
/// <param name="processName"></param>
/// <returns></returns>
  private static bool IsExistProcess(string processName)
        {
            Process[] MyProcesses = Process.GetProcessesByName(processName);
            if (MyProcesses != null && MyProcesses.Length > 0)
            {
                return true;
            }
            return false;
        }

2.建一个windows services 工程,添加一个System.Timers.Timer来使用.

  // Create a timer with a 60*5 second interval.
  aTimer = new System.Timers.Timer(60000*30); 

  aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
  aTimer.Enabled = true;

  在OnTimedEvent里写要处理的内容.

 

代码
 
   
if ( ! IsExistProcess( " FormDemo " ))
{
Process p
= new Process();
string location = System.Reflection.Assembly.GetExecutingAssembly().Location;
string dir = location.Substring( 0 , location.LastIndexOf( " \\ " ) + 1 );
p.StartInfo.FileName
= dir + " FormDemo.exe " ;
p.Start();
}
       }

3.添加安装程序.我使用localsystem使用户,自动启动

在ServiceProcessInstaller的onCommited事件里设置服务可以与桌面交互,否则会看不到界面,虽然进程里面会有.

 

代码
 
   
// 允许桌面交互
private void serviceProcessInstaller_Committed( object sender, InstallEventArgs e)
{
try
{
ConnectionOptions myConOptions
= new ConnectionOptions();
myConOptions.Impersonation
= ImpersonationLevel.Impersonate;
ManagementScope mgmtScope
= new System.Management.ManagementScope( @" root\CIMV2 " , myConOptions);
mgmtScope.Connect();
ManagementObject wmiService
= new ManagementObject( " Win32_Service.Name=' " + serviceInstaller.ServiceName + " ' " );
ManagementBaseObject InParam
= wmiService.GetMethodParameters( " Change " );
InParam[
" DesktopInteract " ] = true ;
ManagementBaseObject OutParam
= wmiService.InvokeMethod( " Change " , InParam, null );

#region Windows服务安装后自动启动
Process p
= new Process();
p.StartInfo.FileName
= " cmd.exe " ;
p.StartInfo.UseShellExecute
= false ;
p.StartInfo.RedirectStandardInput
= true ;
p.StartInfo.RedirectStandardOutput
= true ;
p.StartInfo.RedirectStandardError
= true ;
p.StartInfo.CreateNoWindow
= true ;
p.Start();
string Cmdstring = " net start " + serviceInstaller.ServiceName;
p.StandardInput.WriteLine(Cmdstring);
p.StandardInput.WriteLine(
" exit " );
#endregion

}
catch
{
EventLog.WriteEvent(
" test failer " , null , null , null );
}

}

 

第一次我使用安装项目进行安装,没有顺利进行,后来改为批处理了,直接把对应版本的installutil.exe拷由到服务所在路径,然后

installutil /i  myservice.exe

net start myservice

pause

 

转载于:https://www.cnblogs.com/huaxiaoyao/archive/2011/01/04/1925482.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值