且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Windows窗体运行Windows服务

更新时间:2023-02-05 18:12:10

没有run from这样的东西。如果要将服务应用程序作为某个其他进程的子进程(例如Forms应用程序),它可以运行,但是......它不会作为服务运行。正确开发的服务应用程序只有在由服务控制器托管时才能用作服务。为此,您需要安装服务。安装后,可以使用Windows小程序服务启动该服务;此外,如果您的服务配置为自动启动,它将在系统启动时启动。



您所能做的就是连接已安装的服务,运行或者停止一个,并通过服务控制器操纵它。您可以使用类 System.ServiceProcess.ServiceController 从应用程序执行此操作:

ServiceController类(System.ServiceProcess) [ ^ ]。



你没有解释你的目的;你的问题看起来很奇怪,所以我不知道为什么你认为你需要运行服务是如此奇怪的方式。但实际上,你可以做类似的事情。您可以开发一个双用途应用程序,如果从shell或您的应用程序启动,则表现为普通应用程序,如果从服务控制器启动,则作为Windows服务。应用程序的这两种模式可以共享代码的主要部分,因此您可以在不安装服务的情况下调试此共享代码。对实际运行的服务进行所有调试要困难得多。有关更多详细信息,请参阅我以前的答案:使用UI配置Windows服务 [ ^ ] 。



-SA
There is no such thing as "run from". If you want to make a service application a child process of some other process, such as your Forms application, it can run, but… it won't run as a service. The properly developed service application can only work as a service if it is hosted by a service controller. For that purpose, you need to install the service. Once installed, the service can be started by using the Windows applet "Services"; also, if your service is configured to auto-start, it will start on the system start.

All you can do is to connect to an already installed service, running or stopped one, and manipulate it through the service controller. You can do it from your application by using the class System.ServiceProcess.ServiceController:
ServiceController Class (System.ServiceProcess)[^].

You did not explain your purpose; and your question looks really weird, so I don't know why would you think that you need to run a service is such a weird way. But actually, you can do something similar. You can develop a dual-purpose application which behaves as an ordinary application if started from the shell or your application, and as Windows service if started from the service controller. These two modes of your application can share major part of your code, so you would be able to debug this shared code without installing the service. Doing all the debugging on an actually running service is much harder. Please see my past answer for further detail: Configure Windows Service with UI[^].

—SA


你没有运行服务,这个想法是那样的他们总是跑步,等待有事可做。为了让服务知道它是否有事可做,你需要某种通信机制,所以服务可以轮询数据库,监听TCP连接,查看新文件夹等等,这一切都取决于服务是什么是如何编码的。
You don't "run" services, the idea is that they are always running and waiting for something to do. In order for the service to know if it has something to do you need some kind of communication mechanism, so the service can poll a database, listen for a TCP connection, watch a folder for new files etc etc, it all depends what the service does and how it is coded.