WIN服务程序调用其他程序

在一般的C#的应该程序中,我们可以使用

/Process myp = new Process();
            //myp.StartInfo.FileName = @"E:\\VS\\test\\WindowsApplication1\\WindowsApplication1\\bin\\Debug\\WindowsApplication1.exe";
            //myp.StartInfo.Verb = "Open";
            //myp.StartInfo.CreateNoWindow = false;
            //myp.Start();

以上代码来调用另一个程序,但如果我们想做成用服务的形式只是用上面的代码有可能会使服务出错,或者不能显示出想要的应该程序。
其实,出现这问题的关键就是允许服务与桌面交互的属性没有设置好,手工设置的方法是:
选择你建好的服务,右键——》属性-》登陆-》把允许服务与桌面交互勾上。这样就可以在服务中调用程序了。
那在这属性中可以设置,应该在安装时的时候代码也可以实现的。在网上找了一下,也找到了
在安装文件的CS文中插入一个serviceInstaller的组件,在这组件的方法中增加

 private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
        {
            ConnectionOptions coOptions = new ConnectionOptions();
            ServiceController ServiceController = new ServiceController("textwinservice");
            coOptions.Impersonation = ImpersonationLevel.Impersonate;

            ManagementScope mgmtScope = new System.Management.ManagementScope(@"root\CIMV2", coOptions);

            mgmtScope.Connect();

            ManagementObject wmiService;

            wmiService = new ManagementObject("Win32_Service.Name='" + ServiceController.ServiceName + "'");

            ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");

            InParam["DesktopInteract"] = true;

            ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);

            ServiceController.Start();   
        }
       

那当我们安装好服务时,就会自动把刚才那个属性勾上。

代码下载/Files/milk3q/WatchFileService.rar代码比较乱,已经12点了,没时间整理了,我要睡了。

posted on 2008-06-03 00:03  笨雀  阅读(280)  评论(0编辑  收藏  举报