本文主要介绍了创建系统服务;开启服务,启动程序。具有一定的参考价值,下面跟着小编一起来看下吧
正文
C#不登录电脑启动程序
阅读目录
- 创建系统服务
- 开启服务,启动程序
我们知道开机自启动程序如果在用户不登录的情况下是不启动的,但是服务类程序是可以跨过用户登录启动的,例如iis服务,sql服务。如果我们已经写好了桌面应用程序,又希望他开机自启动,那就需要借助系统服务在未登录的时候打开程序。
创建系统服务
在vs中创建windows服务:

在service的onstart方法中,启动程序,代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
protected override void onstart(string[] args){ if (!isexistprocess("程序名")) { //程序路径 string exepath = ""; process.start(exepath); } fileinfo fi = new fileinfo(path + "\\info.txt"); using (filestream stream = fi.openwrite()) { streamwriter streamwriter = new streamwriter(stream); streamwriter.write("服务启动日期:" + datetime.now.tostring()); streamwriter.flush(); streamwriter.close(); }}protected override void onstop(){ string path = appdomain.currentdomain.basedirectory; fileinfo fi = new fileinfo(path + "\\info.txt"); using (filestream stream = fi.openwrite()) { streamwriter streamwriter = new streamwriter(stream); streamwriter.write("服务关闭日期:" + datetime.now.tostring()); streamwriter.flush(); streamwriter.close(); }}/// <summary>/// 判断进程是否开启/// </summary>/// <param name="processname"></param>/// <returns></returns>private bool isexistprocess(string processname){ process[] myprocesses = process.getprocesses(); foreach (process myprocess in myprocesses) { if (myprocess.processname.compareto(processname) == 0) { return true; } } return false;} |
在service的设计视图添加安装程序:


设置processinstaller的account为localsystem
设置serviceinstaller的starttype为automatic,servicename和description为进程中显示的名字和描述
回到目录
开启服务,启动程序
程序编译好,取出bin文件夹,添加开启服务和关闭服务的批处理文件,如下图:

开启桌面程序的关键点,更改进程登录模式

安装后启动.bat内容为:
|
1
2
3
4
5
6
7
8
|
安装服务c:\windows\microsoft.net\framework\v4.0.30319\installutil autostart.exe停止服务sc stop autostarthik更改登录sc config autostarthik type= interact type= own启动服务sc start autostarthik |
卸载服务.bat内容为:
|
1
2
|
段落引sc stop autostarthikc:\windows\microsoft.net\framework\v4.0.30319\installutil autostart.exe /u |
至此执行启动服务的bat文件后完成,开机自启动桌面程序。
注:有朋友在问题中提到了运行的问题,我在这里截张图
运行后的程序如果有和桌面交互的语句,会有以下提示,如你messgebox语句

点进去之后会有一个全新的桌面,上面运行着你通过服务启动的程序,如果和桌面不交互,你在进程里可以看到exe正在运行,他的显示界面在交互式服务里自己安静的运行。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持米米素材网!
原文链接:http://www.cnblogs.com/kaoleba/p/6337040.html#_labelTop

发表评论