在c#创建的开机自启动服务里,调用外部可执行文件有以下问题:
1、带窗口的交互式的exe文件调用后,实际并没有被执行;
2、服务是随windows启动的,服务启动后可能windows桌面还没出来,会报错误,导致程序无法执行;
3、安装服务需管理员权限
等问题。
对上面的一些问题进行处理:
1、调用带窗口的交互式的exe文件,主要是Interop.cs文件,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks; namespace ConsoleWithWindowsService
{
class Interop
{
public static void CreateProcess(string app, string path)
{
bool result;
IntPtr hToken = WindowsIdentity.GetCurrent().Token;
IntPtr hDupedToken = IntPtr.Zero; PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa); STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si); int dwSessionID = WTSGetActiveConsoleSessionId();
result = WTSQueryUserToken(dwSessionID, out hToken); if (!result)
{
ShowMessageBox("WTSQueryUserToken failed", "AlertService Message");
} result = DuplicateTokenEx(
hToken,
GENERIC_ALL_ACCESS,
ref sa,
(int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
(int)TOKEN_TYPE.TokenPrimary,
ref hDupedToken
); if (!result)
{
ShowMessageBox("DuplicateTokenEx failed", "AlertService Message");
} IntPtr lpEnvironment = IntPtr.Zero;
result = CreateEnvironmentBlock(out lpEnvironment, hDupedToken, false); if (!result)
{
ShowMessageBox("CreateEnvironmentBlock failed", "AlertService Message");
} result = CreateProcessAsUser(
hDupedToken,
app,
String.Empty,
ref sa, ref sa,
false, , IntPtr.Zero,
null, ref si, ref pi); if (!result)
{
int error = Marshal.GetLastWin32Error();
string message = String.Format("CreateProcessAsUser Error: {0}", error);
ShowMessageBox(message, "AlertService Message");
} if (pi.hProcess != IntPtr.Zero)
CloseHandle(pi.hProcess);
if (pi.hThread != IntPtr.Zero)
CloseHandle(pi.hThread);
if (hDupedToken != IntPtr.Zero)
CloseHandle(hDupedToken);
} [StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
} [StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public Int32 dwProcessID;
public Int32 dwThreadID;
} [StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public Int32 Length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
} public enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
} public enum TOKEN_TYPE
{
TokenPrimary = ,
TokenImpersonation
} public const int GENERIC_ALL_ACCESS = 0x10000000; [DllImport("kernel32.dll", SetLastError = true,
CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", SetLastError = true,
CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern bool CreateProcessAsUser(
IntPtr hToken,
string lpApplicationName,
string lpCommandLine,
ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
bool bInheritHandle,
Int32 dwCreationFlags,
IntPtr lpEnvrionment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
ref PROCESS_INFORMATION lpProcessInformation); [DllImport("advapi32.dll", SetLastError = true)]
public static extern bool DuplicateTokenEx(
IntPtr hExistingToken,
Int32 dwDesiredAccess,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
Int32 ImpersonationLevel,
Int32 dwTokenType,
ref IntPtr phNewToken); [DllImport("wtsapi32.dll", SetLastError = true)]
public static extern bool WTSQueryUserToken(
Int32 sessionId,
out IntPtr Token); [DllImport("userenv.dll", SetLastError = true)]
static extern bool CreateEnvironmentBlock(
out IntPtr lpEnvironment,
IntPtr hToken,
bool bInherit); public static IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
public static void ShowMessageBox(string message, string title)
{
int resp = ;
WTSSendMessage(
WTS_CURRENT_SERVER_HANDLE,
WTSGetActiveConsoleSessionId(),
title, title.Length,
message, message.Length,
, , out resp, false);
} [DllImport("kernel32.dll", SetLastError = true)]
public static extern int WTSGetActiveConsoleSessionId(); [DllImport("wtsapi32.dll", SetLastError = true)]
public static extern bool WTSSendMessage(
IntPtr hServer,
int SessionId,
String pTitle,
int TitleLength,
String pMessage,
int MessageLength,
int Style,
int Timeout,
out int pResponse,
bool bWait);
}
}

在服务调用问文件WindowsService.cs里面这样引用
Interop.CreateProcess(@"d:\getp.exe", @"C:\Windows\System32\"); //执行
这里的exe可以是任意的。
2、在服务里建了个线程,延时执行exe文件,避免了第2个问题,同时循环执行,很多软件的服务不断弹出新闻广告就这这样子。
3、管理员权限问题:
在项目上点右键选“属性”,选择“安全性”,勾选复选框“启用ClickOnce”

最后返回“安全性”,将复选框“启用ClickOnce”去掉。

这样就可以管理员权限安装了。

本例安装进程名为“我的数据服务”,每隔200秒执行getp.exe文件。
运行时可选择“1”进行安装,“3”进行卸载,安装完毕后在服务里可以看到“我的数据服务”项目。

比写注册表添加开机启动好多了,就算放个木马也不会报病毒了

下载:http://pan.baidu.com/s/1pLRnm8j

初学c# -- c#创建开机自启服调用外部交互式exe文件的更多相关文章

  1. 如何管理linux开机自启服务

    如何管理linux开机自启服务? 自启动服务非常重要,例如 (1)需要手动添加希望自启的服务,如安装svn后没有自动添加,就需要我们手动加入(2)安装某些程序后,自动加到自启动了,但我们不需要,需要手 ...

  2. android 简单的开机自启

    今天我们主要来探讨android怎么让一个service开机自动启动功能的实现.Android手机在启动的过程中会触发一个Standard Broadcast Action,名字叫android.in ...

  3. Linux(CentOS6.5)下Nginx注册系统服务(启动、停止、重启、重载等)&设置开机自启

    本文地址http://comexchan.cnblogs.com/ ,作者Comex Chan,尊重知识产权,转载请注明出处,谢谢! 完成了Nginx的编译安装后,仅仅是能支持Nginx最基本的功能, ...

  4. centos7安装docker并设置开机自启以及常用命令

    Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化.容器是完全使用沙箱机制,相互之间不会有任何 ...

  5. redis设置开机自启

    开机自启动redis(其他服务类似) centos 7以上是用Systemd进行系统初始化的,Systemd 是 Linux 系统中最新的初始化系统(init),它主要的设计目标是克服 sysvini ...

  6. Supervisor进程管理&开机自启

    这几天在用supervisor管理爬虫和Flask, 每次都记不住命令,花点时间记录下. supervisor是一个进程管理工具,用来启动.停止.重启和监测进程.我用这个东西主要用来监测爬虫和Flas ...

  7. windows server 2008 R2之tomcat开机自启

    方法一: 写一个批处理文件autostartup.bat用来启动tomcat,内容如下.复制时不要把复制内容也复制进去 set CATALINA_HOME=C:\apache-tomcat-8.5.3 ...

  8. Ubuntu 16.04开机自启Nginx简单脚本

    本文要记述的是最简单的Ubuntu下开机自启 nginx的脚本 这里将nginx装在了/usr/local/nginx目录下,nginx本身没有注册成服务,所以直接使用服务开机自启是不行的,除非自己写 ...

  9. linux Nginx服务开机自启

    linux Nginx服务开机自启 Nginx 是一个很强大的高性能Web和反向代理服务器.虽然使用命令行可以对nginx进行各种操作,比如启动等,但是还是根据不太方便.下面介绍在linux下安装后, ...

随机推荐

  1. 10.python面向对象进阶功能

    isinstance(obj,cls)和issubclass(sub,super)(1)isinstance(obj,cls)检查一个对象obj是否是一个类cls的实例(2)issubclass(su ...

  2. python装饰器的详细解析

    什么是装饰器? python装饰器(fuctional decorators)就是用于拓展原来函数功能的一种函数,目的是在不改变原函数名(或类名)的情况下,给函数增加新的功能. 这个函数的特殊之处在于 ...

  3. vs+qt 运行过程出现cannot run rc.exe

    刚开始,我按照网上的一堆教程在qt creator中设置了各种东西,设置完以后,运行时出现cannot run rc.exe,根据百度,将C:\Program Files (x86)\Windows ...

  4. JavaScript数据类型(第一天)

    ECMAScript为JavaScript的标准,javascript为网景公司定义,但并不标准,所以欧洲的组织定义了ESMAScript,定义了网页脚本的标准. js组成 ECMAScript js ...

  5. TreeSet的两种排序方式,含Comparable、Comparator

    1.排序的引入 由于TreeSet可以实现对元素按照某种规则进行排序,例如下面的例子 public class TreeSetDemo { public static void main(String ...

  6. 1T硬盘获3T体验 彻底解决NVR存储时间短的问题

    随着高清技术的进步,现在300W和400W的IPC越来越普及,但同时带来了更多的成本及存储便利问题.“硬盘存了7天就满了”.“同样大小的硬盘,存储时间越来越短”......为啥你的NVR不能存更长的时 ...

  7. 记录一下我在lubuntu里面用到的工具

    文本编辑:Atom 文本对比:Beyond Compare 数据库工具:dbeaver Git工具:GitKraKen SVN工具:RapidSVN 网页编程工具:WebStorm 另外,14.04版 ...

  8. Cannot change version of project facet Dynamic Web Module to 2.4问题解决

    问题现象: eclipse中,有个maven web项目,报错:Cannot change version of project facet Dynamic Web Module to 2.4,截图如 ...

  9. 报错:Exception in thread "main" com.typesafe.config.ConfigException$UnresolvedSubstitution

    报错现象: 报错原因: pom文件中的jar包太高,可以降低jar包的版本号. 报错解决: 我将2.11换成了2.10,即可解决. <dependency> <groupId> ...

  10. mysqli字符编码

    mysqli 字符编码: 汉字编码: 1.gbk 最久的编码格式,不能写繁体: 2.国内的gb2312: 3.国际的标准:utf-8; 查看数据库的字符编码: show variables like ...