windows 服务创建/运行/停止

来源:互联网 发布:c语言流 编辑:程序博客网 时间:2024/06/10 14:59

#include <winsvc.h>
void CStartServiceDlg::OnBnClickedButton1()
{
       
// 打开服务管理对象
    SC_HANDLE hSC = ::OpenSCManager( NULL, 
                        NULL, GENERIC_EXECUTE);
    
if( hSC == NULL)
    
{
        TRACE( 
"open SCManager error");
        
return;
    }

    
// 打开www服务。
    SC_HANDLE hSvc = ::OpenService( hSC, "W3SVC",
        SERVICE_START 
| SERVICE_QUERY_STATUS | SERVICE_STOP);
    
if( hSvc == NULL)
    
{
        TRACE( 
"Open www erron。");
        ::CloseServiceHandle( hSC);
        
return;
    }

    
// 获得服务的状态
    SERVICE_STATUS status;
    
if( ::QueryServiceStatus( hSvc, &status) == FALSE)
    
{
        TRACE( 
"Get Service state error。");
        ::CloseServiceHandle( hSvc);
        ::CloseServiceHandle( hSC);
        
return;
    }

    
//如果处于停止状态则启动服务,否则停止服务。
    if( status.dwCurrentState == SERVICE_RUNNING)
    
{
        
// 停止服务
        if( ::ControlService( hSvc, 
          SERVICE_CONTROL_STOP, 
&status) == FALSE)
        
{
            TRACE( 
"stop service error。");
            ::CloseServiceHandle( hSvc);
            ::CloseServiceHandle( hSC);
            
return;
        }

        
// 等待服务停止
        while( ::QueryServiceStatus( hSvc, &status) == TRUE)
        
{
            ::Sleep( status.dwWaitHint);
            
if( status.dwCurrentState == SERVICE_STOPPED)
            
{
                AfxMessageBox( 
"stop success。");
                ::CloseServiceHandle( hSvc);
                ::CloseServiceHandle( hSC);
                
return;
            }

        }

    }

    
else if( status.dwCurrentState == SERVICE_STOPPED)
    
{
        
// 启动服务
        if( ::StartService( hSvc, NULL, NULL) == FALSE)
        
{
            TRACE( 
"start service error。");
            ::CloseServiceHandle( hSvc);
            ::CloseServiceHandle( hSC);
            
return;
        }

        
// 等待服务启动
        while( ::QueryServiceStatus( hSvc, &status) == TRUE)
        
{
            ::Sleep( status.dwWaitHint);
            
if( status.dwCurrentState == SERVICE_RUNNING)
            
{
                AfxMessageBox( 
"start success。");
                ::CloseServiceHandle( hSvc);
                ::CloseServiceHandle( hSC);
                
return;
            }

      }

    }

    TRACE( 
"start error。");
    ::CloseServiceHandle( hSvc);
    ::CloseServiceHandle( hSC);
    
return;
}

原创粉丝点击