C#实现一个用于开机启动其他程序的Windows服务
程序的目的和用途:
很多开机启动程序仅仅加在启动项里面,只有登陆后才真正启动。windows服务在开机未进行用户登录前就启动了。正是利用这一点,解决一些服务器自动重启后特定软件也自动启动的问题。
1.新建一个服务项目 visual C#----windows----windows服务;
2.添加一个dataset(.xsd),用于存储启动目标的路径,日志路径等。
在dataset可视化编辑中,添加一个datatable,包含两列 StartAppPath 和 LogFilePath。分别用于存储目标的路径、日志路径。
*我认为利用dataset.xsd存储配置参数的优势在于可以忽略xml解析的具体过程直接使用xml文件。
在dataset中 提供了ReadXml方法用于读取xml文件并将其转换成内存中的一张datatable表,数据很容易取出来!同样,WriteXml方法用于存储为xml格式的文件,也仅仅需要一句话而已。
3. program.cs文件 作为程序入口,代码如下:
view plaincopy to clipboardprint?
using System.Collections.Generic;
using System.ServiceProcess;
using System.Text;
namespace WindowsServices_AutoStart
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
// 同一进程中可以运行多个用户服务。若要将
// 另一个服务添加到此进程中,请更改下行以
// 创建另一个服务对象。例如,
//
// ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new ServiceBase[] { new WindowsServices_AutoStart() };
ServiceBase.Run(ServicesToRun);
}
}
}
using System.Collections.Generic;
using System.ServiceProcess;
using System.Text;
namespace WindowsServices_AutoStart
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
// 同一进程中可以运行多个用户服务。若要将
// 另一个服务添加到此进程中,请更改下行以
// 创建另一个服务对象。例如,
//
// ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new ServiceBase[] { new WindowsServices_AutoStart() };
ServiceBase.Run(ServicesToRun);
}
}
}
4.service.cs主文件,代码如下:
view plaincopy to clipboardprint?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
namespace WindowsServices_AutoStart
{
public partial class WindowsServices_AutoStart : ServiceBase
{
public WindowsServices_AutoStart()
{
InitializeComponent();
}
string StartAppPath =""; //@"F:\00.exe";
string LogFilePath ="";// @"f:\WindowsService.txt";
protected override void OnStart(string[] args)
{
string exePath = System.Threading.Thread.GetDomain().BaseDirectory;
//
if (!File.Exists(exePath + @"\ServiceAppPath.xml"))
{
dsAppPath ds = new dsAppPath();
object[] obj=new object[2];
obj[0]="0";
obj[1]="0";
ds.Tables["dtAppPath"].Rows.Add(obj);
ds.Tables["dtAppPath"].WriteXml(exePath + @"\ServiceAppPath.xml");
return;
}
try
{
dsAppPath ds = new dsAppPath();
ds.Tables["dtAppPath"].ReadXml(exePath + @"\ServiceAppPath.xml");
DataTable dt = ds.Tables["dtAppPath"];
StartAppPath = dt.Rows[0]["StartAppPath"].ToString();
LogFilePath = dt.Rows[0]["LogFilePath"].ToString();
}
catch { return; }
if (File.Exists(StartAppPath))
{
try
{
Process proc = new Process();
proc.StartInfo.FileName = StartAppPath; //注意路径
//proc.StartInfo.Arguments = "";
proc.Start();
}
catch (System.Exception ex)
{
//MessageBox.Show(this, "找不到帮助文件路径。文件是否被改动或删除?\n" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
FileStream fs = new FileStream(LogFilePath, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine("WindowsService: Service Started" + DateTime.Now.ToString() + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
fs.Close();
}
}
protected override void OnStop()
{
try
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
FileStream fs = new FileStream(LogFilePath, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine("WindowsService: Service Stopped " + DateTime.Now.ToString() + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
fs.Close();
}
catch
{
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
namespace WindowsServices_AutoStart
{
public partial class WindowsServices_AutoStart : ServiceBase
{
public WindowsServices_AutoStart()
{
InitializeComponent();
}
string StartAppPath =""; //@"F:\00.exe";
string LogFilePath ="";// @"f:\WindowsService.txt";
protected override void OnStart(string[] args)
{
string exePath = System.Threading.Thread.GetDomain().BaseDirectory;
//
if (!File.Exists(exePath + @"\ServiceAppPath.xml"))
{
dsAppPath ds = new dsAppPath();
object[] obj=new object[2];
obj[0]="0";
obj[1]="0";
ds.Tables["dtAppPath"].Rows.Add(obj);
ds.Tables["dtAppPath"].WriteXml(exePath + @"\ServiceAppPath.xml");
return;
}
try
{
dsAppPath ds = new dsAppPath();
ds.Tables["dtAppPath"].ReadXml(exePath + @"\ServiceAppPath.xml");
DataTable dt = ds.Tables["dtAppPath"];
StartAppPath = dt.Rows[0]["StartAppPath"].ToString();
LogFilePath = dt.Rows[0]["LogFilePath"].ToString();
}
catch { return; }
if (File.Exists(StartAppPath))
{
try
{
Process proc = new Process();
proc.StartInfo.FileName = StartAppPath; //注意路径
//proc.StartInfo.Arguments = "";
proc.Start();
}
catch (System.Exception ex)
{
//MessageBox.Show(this, "找不到帮助文件路径。文件是否被改动或删除?\n" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
FileStream fs = new FileStream(LogFilePath, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine("WindowsService: Service Started" + DateTime.Now.ToString() + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
fs.Close();
}
}
protected override void OnStop()
{
try
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
FileStream fs = new FileStream(LogFilePath, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine("WindowsService: Service Stopped " + DateTime.Now.ToString() + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
fs.Close();
}
catch
{
}
}
}
}
5.启动调试,成功时也会弹出一个对话框大致意思是提示服务需要安装。
6.把Debug文件夹下面的.exe执行程序,安装为windows系统服务,安装方法网上很多介绍。我说一种常用的:
安装服务
访问项目中的已编译可执行文件所在的目录。
用项目的输出作为参数,从命令行运行 InstallUtil.exe。在命令行中输入下列代码:
installutil yourproject.exe
卸载服务
用项目的输出作为参数,从命令行运行 InstallUtil.exe。
installutil /u yourproject.exe
至此,整个服务已经编写,编译,安装完成,你可以在控制面板的管理工具的服务中,看到你编写的服务。
7.安装好了之后在系统服务列表中可以管理服务,这时要注意将服务的属性窗口----登陆----“允许于桌面交互”勾选!这样才能在启动了你要的目标程序后不单单存留于进程。在桌面上也看得到。
8.关于卸载服务,目前有两个概念:一是禁用而已;一是完全删除服务。 前者可以通过服务管理窗口直接完成。后者则需要进入注册表“HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services”找到服务名称的文件夹,整个删掉,重新启动电脑后,服务消失。
9.扩展思考:经过修改代码,还可以实现:启动目标程序之前,检测进程中是否存在目标程序,存在则不再次启动
转载于:https://www.cnblogs.com/freedom831215/archive/2009/10/03/1577669.html
相关文章:

Mythic推出“万能”芯片,任何设备都能一秒变身智能产品
我们身边已经出现了一些能够实现语音控制的设备。不过,无论是智能手机还是智能扬声器,都必须先连接到云端,才能实现语音控制。现在,一家叫做Mythic的初创公司推出的新型的芯片和软件将改变这一情况。它无需通过云端就能在本地设备…
【怎样写代码】参数化类型 -- 泛型(四):泛型之类型参数约束
如果喜欢这里的内容,你能够给我最大的帮助就是转发,告诉你的朋友,鼓励他们一起来学习。 If you like the content here, you can give me the greatest help is forwarding, tell your friends, encourage them to learn together.

matlab实验是啥,matlab实验心得体会
matlab实验心得体会这个就是我自己做出来的,发现用soundsc听出来还行,但是用wavwrite就变的很难听。后来发现PB写的很好,而且还能够把前面一段没有噪音的部分给保存下来,我就看了他的代码,有几点体会:1.将代…

Silverlight中文件的生成操作与其对应的获取方法
文件生成操作:Silverlight里的资源文件(图片、视频、字体、XML、XAML等) 生成操作属性选择不同选项时,文件的生成方式和存储位置会有相应变化,下面说一下几个常用的选项:1、 Page:一般xaml文件都用这个。2、 Compile&a…

2017SDN市场一片繁荣,全球企业纷纷“亮剑“
据国外媒体报道,爱尔兰市场研究机构Research and Markets发布的数据显示,到2023年,全球运营商软件定义网络市场预计将达到95亿美元。预计运营商软件定义网络将在未来六年中以42.3%的年复合率增长。强大的市场前景,使得全球各大运营…
【怎样写代码】参数化类型 -- 泛型(五):泛型类
如果喜欢这里的内容,你能够给我最大的帮助就是转发,告诉你的朋友,鼓励他们一起来学习。 If you like the content here, you can give me the greatest help is forwarding, tell your friends, encourage them to learn together.

kerberos java实现,基于kerberos实现jaas登录
这段时间在做hadoop和kerberos的整合,顺便看了jaas和kerberos,这里给出使用kerberos登录模块的jaas例子。前提条件1.kerberos已经安装,principal已经创建,这里用的principal是已经建好的nn/adminpsy.com;2.客户端配置了kerberos&a…
【怎样写代码】参数化类型 -- 泛型(六):泛型接口
如果喜欢这里的内容,你能够给我最大的帮助就是转发,告诉你的朋友,鼓励他们一起来学习。 If you like the content here, you can give me the greatest help is forwarding, tell your friends, encourage them to learn together.

多媒体视像会议中音视频矩阵的用途
在现代多媒体会议室,为了满足不同演示场合的需求,通常会具备多种不同的音视频信号源和显示终端,虽然这些音视频信号源和显示终端也可能会同时具备复合视频(Composite-Video)、超级视频(S-Video)…

winsock select
MSDN中,有: select The select function determines the status of one or more sockets, waiting if necessary, to perform synchronous I/O.int select(int nfds,fd_set* readfds,fd_set* writefds,fd_set* exceptfds,const struct timeval* timeout …

matlab llc谐振电路,一个菜鸟对LLC谐振知识的渴望
admin离线LV9管理员积分:30301|主题:2337|帖子:8925积分:30301管理员2015-5-27 14:55:14期待ingshyshihouyun积分:5664|主题:152|帖子:2386积分:5664LV8副总工程师2015-5-27 15:01:18首先要知道为什么要用L…

启用IIS的Gzip压缩 【转】
现代的浏览器IE6和Firefox都支持客户端Gzip,也就是说,在服务器上的网页,传输之前,先使用Gzip压缩再传 输给客户端,客户端接收之后由浏览器解压显示,这样虽然稍微占用了一些服务器和客户端的CPU,…
【怎样写代码】参数化类型 -- 泛型(七):泛型方法
如果喜欢这里的内容,你能够给我最大的帮助就是转发,告诉你的朋友,鼓励他们一起来学习。 If you like the content here, you can give me the greatest help is forwarding, tell your friends, encourage them to learn together.

新疆弃光量下降14% 弃光问题仍然难解
风力与太阳能资源丰沛的中国新疆地区,同时也是中国弃光、弃风限电问题最严重的地区。好消息是,新疆维吾尔自治区发改委指出,新疆今年第一季的弃光与弃风量分别较去年同期降低了14.4%和14%;然而,整体弃光问题仍然难解。…

ueditor php 附件,ueditor单独调用上传附件和图片的功能
第一步, 引入文件第二步 html元素调用的页面:上传图片上传文件第三步 编写js代码var _editor;$(function() {//重新实例化一个编辑器,防止在上面的editor编辑器中显示上传的图片或者文件_editor UE.getEditor(upload_ue);_editor.ready(function () {//…

动网论坛数据库字段表说明
address ip表ip1 ip地址开始ip2 ip地址结束country 国家city 城市admin 管理员表id 管理员自编idusername 用户名 password 管理员后台登录密码flag 管理权限(0519)lastlogin 管理员登录后台最后一次时间lastloginip 管理员最后一次登陆后台ipadduser 登…
【怎样写代码】参数化类型 -- 泛型(八):泛型委托
如果喜欢这里的内容,你能够给我最大的帮助就是转发,告诉你的朋友,鼓励他们一起来学习。 If you like the content here, you can give me the greatest help is forwarding, tell your friends, encourage them to learn together.

GfK公司将IT设备移至Equinix公司在法兰克福的数据中心
日前据悉,德国市场研究机构GfK公司将其所有IT基础设施从纽伦堡的三个数据中心转移到Equinix公司最近在法兰克福开通的一个数据中心。该举措将巩固GfK公司在EMEA(欧洲、中东、非洲)地区的数据业务,提高效率,并获得更多的…

php签名是做什么用的,这个签名在PHP中意味着什么()?
在PHP的语法中,这意味着该函数返回引用而不是值.例如:$foo foo;function & get_foo_ref (){global $foo;return $foo;}// Get the reference to variable $foo stored into $bar$bar & get_foo_ref();$bar bar;echo $foo; // Outputs bar, since $bar re…

静态构造函数趣谈!
类的静态构造函数也叫类型构造器,静态构造器,他调用的时刻由CLR来控制:CLR会选择如下时间之一来调用静态构造函数: 1,在类型的第一个实例创建之前,或类型的非继承字段或成员第一次访问之前。这里的“之…
【怎样写代码】参数化类型 -- 泛型(九):泛型代码中的default关键字
如果喜欢这里的内容,你能够给我最大的帮助就是转发,告诉你的朋友,鼓励他们一起来学习。 If you like the content here, you can give me the greatest help is forwarding, tell your friends, encourage them to learn together.

Facebook失误泄露反恐审查员信息 生命或受威胁
北京时间19日下午WSJ讯Facebook(FB)因疏忽将负责审核疑似恐怖分子和其它群组发布内容的审查员姓名居然暴露给了这些审查对象,公司上周五称这一漏洞已修复。 Facebook发言人称,大约1000名Facebook审查员受到在活动日志中公开审查员…

LSB图像信息隐藏算法matlab,实验二LSB信息隐藏实验.doc
实验二LSB信息隐藏实验.doc实验二LSB信息隐藏实验综合评分:【实验目的】:掌握MATLAB基木操作实现LSB信息隐藏和提取【实验内容】:(请将你实验完成的项11涂“■“)实验完成形式:■用MATLAB函数实现LSB信息隐藏和提取□其它:(请注明…

关于程序员的政治(转)
其实一直都不太懂得办公室的政治,我出来一年多了,自己喜欢做的事情没做到,当初也很傻很天真的觉得事业单位恶心,企业只要有能力就一定有出头之日,拒绝了同学好友的要求。现在悔到肠子都青了。下面只是我总结的一点关于…
【机器学习】基于蚁群算法的多元非线性函数极值寻优
如果喜欢这里的内容,你能够给我最大的帮助就是转发,告诉你的朋友,鼓励他们一起来学习。 If you like the content here, you can give me the greatest help is forwarding, tell your friends, encourage them to learn together.

东方日升重磅推出白色双玻组件 助力推动度电成本下滑
近日,为期3天的日本国际太阳能展览会PVExpo2017在日本东京圆满落幕。A股光伏龙头企业东方日升携60片单多晶组件、72片单多晶组件与白色多晶双玻组件等一系列高效产品亮相展会,并凭借良好的抗PID特性、优异的输出功率以及名列全球第一梯队的品牌备受日本光…

php -find(),php – beforeFind()添加条件
使用beforeFind(),如果希望find使用它,则应返回已修改的$queryData数组.这是你目前的问题.public function beforeFind($queryData) {parent::beforeFind();$queryData[conditions] array(client_id > 2);return $queryData;}但是,您还有其他一些小问题可能会导致您遇到问题…

“北京今年入冬的第一场雪”,纪念博客园写日志一年了
今天是2009年11月1日,北京下了入冬以来的第一场雪,就在昨天我还以为北京还是秋季,可是今天早上醒来看到外面飘落的大雪,已经意识到北京的冬天已经到来了 来博客园写博客一年了,结识了很多朋友,也为社区贡献…

从特急到难产 光伏增补项目抢不抢630?
2016年12月22日晚,国家能源局以特急形式发布国能新能〔2016〕383号《关于调整2016年光伏发电建设规模有关问题的通知》,要求每个省(自治区、直辖市)追加规模最多不超过100万kW,超过50万kW以上的明年不再下达其新增建设…
【计算机视觉】EmguCV学习笔记(1)Hello World
如果喜欢这里的内容,你能够给我最大的帮助就是转发,告诉你的朋友,鼓励他们一起来学习。 If you like the content here, you can give me the greatest help is forwarding, tell your friends, encourage them to learn together.