windows 服务启动外部程序

2021-07-13 18:07

阅读:335

标签:sage   stop   文章   proc   token   rsh   temp   string   ons   

服务使用Process启动外部程序没窗体

在WinXP和Win2003环境中,安装服务后,右键单击服务“属性”-“登录”选项卡-选择“本地系统帐户”并勾选“允许服务与桌面交互”即可.

在Win7及以后的环境中,由于微软加强了权限管理,将此功能禁用,需要引用第三方dll (Cjwdev.WindowsApi.dll)

链接: https://pan.baidu.com/s/1P6bBHI_AkOOTxvRTHh06aw 密码: phdj

具体原因分析可参考此文章 :http://www.cnblogs.com/gnielee/archive/2010/04/07/session0-isolation-part1.html

public void AppStart(string appPath,string parms)
        {
            try
            {
                string appStartPath = appPath;
                IntPtr userTokenHandle = IntPtr.Zero;
                ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle);

                ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION();
                ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO();
                startInfo.cb = (uint)Marshal.SizeOf(startInfo);

                ApiDefinitions.CreateProcessAsUser(
                    userTokenHandle,
                    appStartPath,
                    parms,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    false,
                    0,
                    IntPtr.Zero,
                    null,
                    ref startInfo,
                    out procInfo);

                if (userTokenHandle != IntPtr.Zero)
                    ApiDefinitions.CloseHandle(userTokenHandle);

                int _currentAquariusProcessId = (int)procInfo.dwProcessId;
                temppid = _currentAquariusProcessId;
                WriteLog("temppid", _currentAquariusProcessId.ToString());
            }
            catch (Exception ex)
            {
                WriteLog("AppStart", ex.Message);
            }
        }

  

CreateProcessAsUser

  关于参数 lpCommandLine,这里可以放你给被创建进程传递的参数。 注意 C程序在传递参数时需要在参数前加一个空格,因为c程序main函数入参默认第一个参数是模块名称,从第二个参数开始才是你想要传递进去的参数,而参数以空格分隔 所以你要加一个空格啦。

 

关于通过Bat文件安装卸载服务

cd /d %~dp0
sc create MonitorService binpath="%cd%\WindowsService1.exe" start= auto
sc start MonitorService
pause

 

sc stop MonitorService 
sc delete MonitorService 
pause

  

 

 

windows 服务启动外部程序

标签:sage   stop   文章   proc   token   rsh   temp   string   ons   

原文地址:https://www.cnblogs.com/zacklau/p/9567439.html


评论


亲,登录后才可以留言!