windows服务win7中启动外部程序

来源:互联网 发布:linux oracle 重启监听 编辑:程序博客网 时间:2024/04/24 03:13

windows服务中启动外部程序

 private void Timer_Click(Object sender, ElapsedEventArgs e)
        {

            Process[] localByName = Process.GetProcessesByName("360tray.exe");

            //这里的360tray.exe就是你想要执行的程序的进程的名称。基本上就是.exe文件的文件名。

            //localByName得到的是进程中所有名称为"360tray.exe"的进程。
            if (localByName.Length == 0) //如果得到的进程数是0, 那么说明程序未启动,需要启动程序
            {
                Process.Start("c://360tray.exe"); //启动程序 "c://360tray.exe" 是程序的路径
            }

            else

            {

                //如果程序已经启动,则执行这一部分代码

            }
        }

启动服务

服务安装成功以后,并没有启动,我们需要在服务管理器中启动它,并且如果运行的程序是带窗体的程序,还需要修改一下服务的属性。

    进入 控制面板——》管理工具——》服务 打开服务管理器。

    在右侧的服务列表中找到我们刚才安装的服务,服务名称就是第2步中ServiceName属性的内容。这里就是WindowsService1。

    如果运行的程序是带窗体的程序,那么右键单击这个服务 选择“属性”——》 单击“登录”标签(在最上面)——》选择本地系统帐户——》在“允许服务与桌面交互”复选框前打勾——》单击确定退出属性。

    这是,带有窗体的程序才会正常运行。否则只会在进程中看到该程序,但是没有窗体。

    现在可以单击这个服务,然后单击启动来启动这个服务了。


Win7下C#通过Windows Service启动外部程序


下载这两个文件:Cjwdev.WindowsApi.dll,Cjwdev.WindowsApi.xml。引用

using Cjwdev;
using Cjwdev.WindowsApi;

 

try
           {

               appStartPath= “C:\\Deepleo.exe”;
               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,
                 “”,
                   IntPtr.Zero,
                   IntPtr.Zero,
                   false,
                   0,
                   IntPtr.Zero,
                   null,
                   ref startInfo,
                   out procInfo);

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

               _currentAquariusProcessId = (int)procInfo.dwProcessId;
           }
           catch (Exception ex)
           {
            MessageBox.Show(string.Format("Start Application failed, its path is {0} ,exception: {1}", appStartPath, ex.Message));
           }


0 0
原创粉丝点击