VC++启动或停止指定的系统后台服务

方法一:

/* write by jruinet */

// NtServiceControlDlg.cpp : 实现文件
#include "stdafx.h"
#include "NtServiceControl.h"
#include "NtServiceControlDlg.h"
#include ".\ntservicecontroldlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

// CNtServiceControlDlg 对话框
CNtServiceControlDlg::CNtServiceControlDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CNtServiceControlDlg::IDD, pParent)
{
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CNtServiceControlDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CNtServiceControlDlg, CDialog)
    ON_WM_SYSCOMMAND()
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    //}}AFX_MSG_MAP
    ON_BN_CLICKED(IDC_BUTTON3, OnBnClickedButton3)
    ON_WM_CLOSE()
    ON_BN_CLICKED(IDC_BUTTON4, OnBnClickedButton4)
    ON_WM_TIMER()
END_MESSAGE_MAP()


// CNtServiceControlDlg 消息处理程序

BOOL CNtServiceControlDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    // 将\“关于...\”菜单项添加到系统菜单中。

    // IDM_ABOUTBOX 必须在系统命令范围内。
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        CString strAboutMenu;
        strAboutMenu.LoadString(IDS_ABOUTBOX);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }
    szServiceName = "ServiceV2";
    // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
    // 执行此操作
    SetIcon(m_hIcon, TRUE);            // 设置大图标
    SetIcon(m_hIcon, FALSE);        // 设置小图标
    SetTimer(1, 1000, NULL); // 1 second interval
    hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
   // ASSERT(hSCM); 

    // open the service
    hService = OpenService(hSCM,szServiceName,SERVICE_ALL_ACCESS);
   
    return TRUE; // 除非设置了控件的焦点,否则返回 TRUE
}

void CNtServiceControlDlg::ShowStatus()
{
      if (hService)
      {
          // Get the current status
            SERVICE_STATUS ss;
            memset(&ss, 0, sizeof(ss));
            BOOL b = QueryServiceStatus(hService, &ss);
            if(!b) {
                DWORD dwErr = GetLastError();
                ASSERT(0);
            } else {
                dwErr = ss.dwWin32ExitCode;
                dwState = ss.dwCurrentState;
                // If the service is running, send a control request
                // to get its current status
                if (dwState == SERVICE_RUNNING) {
                    b = ::ControlService(hService,
                                         SERVICE_CONTROL_INTERROGATE,
                                         &ss);
                    if (b) {
                        dwErr = ss.dwWin32ExitCode;
                        dwState = ss.dwCurrentState;
                    }
                }
            }

            // close the service handle
          // CloseServiceHandle(hService);
        }

     // close the service control manager handle
     //   CloseServiceHandle(hSCM);

    // See what we got
    char buf[64];
    if (dwErr == 0xFFFFFFFF) {
        SetDlgItemText(IDC_EXITCODE, "<unknown>");
    } else {
        sprintf(buf, "%8.8lXH (%d)", dwErr, dwErr);
        SetDlgItemText(IDC_EXITCODE, buf);
    }

    switch (dwState) {
    case SERVICE_STOPPED:
        strcpy(buf, "Stopped");
        break;
    case SERVICE_START_PENDING:
        strcpy(buf, "Start pending");
        break;
    case SERVICE_STOP_PENDING:
        strcpy(buf, "Stop pending");
        break;
    case SERVICE_RUNNING:
        strcpy(buf, "Running");
        break;
    case SERVICE_CONTINUE_PENDING:
        strcpy(buf, "Continue pending");
        break;
    case SERVICE_PAUSE_PENDING:
        strcpy(buf, "Pause pending");
        break;
    case SERVICE_PAUSED:
        strcpy(buf, "Paused");
        break;
    default:
        strcpy(buf, "<Unknown>");
        break;
    }
    SetDlgItemText(IDC_STATUS, buf);
}

void CNtServiceControlDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
    if ((nID & 0xFFF0) == IDM_ABOUTBOX)
    {
        CAboutDlg dlgAbout;
        dlgAbout.DoModal();
    }
    else
    {        CDialog::OnSysCommand(nID, lParam);
    }
}

// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。

void CNtServiceControlDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // 用于绘制的设备上下文

        SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

        // 使图标在工作矩形中居中
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;
       
        // 绘制图标
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        //ShowStatus();
        CDialog::OnPaint();
    }
}

//当用户拖动最小化窗口时系统调用此函数取得光标显示。
HCURSOR CNtServiceControlDlg::OnQueryDragIcon()
{
    return static_cast<HCURSOR>(m_hIcon);
}

void CNtServiceControlDlg::OnBnClickedButton3()
{
    BOOL b = StartService(hService, 0, NULL);
    if(!b) {
        DWORD dwErr = GetLastError();
       MessageBox("服务当前正在运行,请关闭服务后再重新启动!");
    }
    ShowStatus();
}

void CNtServiceControlDlg::OnClose()
{
     // close the service handle
    CloseServiceHandle(hService);

    // close the service control manager handle
    CloseServiceHandle(hSCM);

    CDialog::OnClose();
}

void CNtServiceControlDlg::OnBnClickedButton4()
{
    // Get the service name

    BOOL b = ControlService(hService,
                            SERVICE_CONTROL_STOP,
                            &ss);
    if(!b) {
        DWORD dwErr = GetLastError();
        MessageBox("服务当前以关闭!");
    }
    ShowStatus();
}

void CNtServiceControlDlg::OnTimer(UINT nIDEvent)
{
    ShowStatus();
    //CDialog::OnTimer(nIDEvent);
}


方法二:
system("net stop <service name>");

原文地址:https://www.cnblogs.com/croot/p/3235127.html