QT operates Windows system services

        Windows services are background applications running on the Windows operating system. They start automatically when the system starts and continue to run in the background without user interaction. The functions of Windows services include but are not limited to the following aspects: 1. Providing system functions: Many Windows services provide system-level functions and services, such as network connections, file sharing, printing services, security authentication, remote management, etc. These services provide infrastructure and functional support to users and other applications. 2. Automated tasks: Windows services can be used to perform automated tasks, such as regular backups, data synchronization, logging, scheduled tasks, etc. They can run in the background without user intervention, providing reliable automation capabilities. 3. Background communication and message passing: Windows services can be used to implement background communication and message passing, such as message queues, inter-process communication, etc. They can pass data and messages between different applications, enabling collaboration and integration between applications. 4. System monitoring and management: Windows services can be used to monitor and manage system status and resources, such as performance monitoring, event logs, service management, etc. They can collect system information, monitor system performance, and provide management interfaces and functions to help administrators maintain and manage the system.
        Windows services are applications that run in the background, providing system-level functions and services, performing automated tasks, implementing background communication and messaging, and monitoring and managing the system. They provide stable, reliable and efficient functional support for Windows operating systems.

        It should be noted that the program needs to be started with administrator privileges before it can operate the service

QT operates Windows system service directory

1 Create a service

2 Delete service

3 Open the service

4 Shut down the service

5 Start the service

6 Stop service

7 automatic start

8 Manual start

9 Inquiry service

10.h source file


 This article is original by the author. Please attach the source of the article and the link to this article when reprinting.

1 Create a service

///@ 创建服务
void MainWindow::newService()
{
    SC_HANDLE schandle = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); //打开服务管理
    SC_HANDLE h = ::CreateService(schandle,
        L"ServiceAPI", //服务名
        L"ServiceAPI-Test", //显示用的服务名
        SERVICE_ALL_ACCESS, //所有访问权限
        SERVICE_WIN32_OWN_PROCESS,  //私有类型
        SERVICE_AUTO_START, //自启动类型
        SERVICE_ERROR_NORMAL, //忽略错误处理
        L"D:/ServiceAPI.exe", //应用程序路径
        nullptr, nullptr, nullptr, nullptr, nullptr);

    ::CloseServiceHandle(h); //关闭
    ::CloseServiceHandle(schandle);//关闭
    ::getchar(); //暂停
}

2 Delete service

///@ 删除服务
void MainWindow::deleteService()
{
    SC_HANDLE schandle = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); //打开服务管理
    SC_HANDLE h = ::OpenService(schandle, L"ServiceAPI", SERVICE_ALL_ACCESS); //打开要删除的服务

    if (h != NULL)
    {
        if (::DeleteService(h))
        {
            qDebug() << "Service deleted successfully.";
        }
        else
        {
            if(GetLastError() == 1072)
                qDebug() << "Please restart Windows .....";
            else
                qDebug() << "Failed to delete service. Error code: " << GetLastError();
        }
        ::CloseServiceHandle(h); //关闭服务句柄
    }
    else
    {
        qDebug() << "Failed to open service. Error code: " << GetLastError();
    }

    ::CloseServiceHandle(schandle); //关闭服务管理句柄
    ::getchar(); //暂停
}

3 Open the service

///@ 打开服务
void MainWindow::openService()
{
    // 打开服务控制管理器
    hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);

    if (hSCM == NULL) {
        qDebug() << "OpenSCManager failed with error:" << GetLastError();
        return;
    }

    // 打开Windows 服务
    hService = OpenService(hSCM, TEXT("SQLWriter"), SERVICE_ALL_ACCESS);

    if (hService == NULL) {
        qDebug() << "OpenService failed with error:" << GetLastError();
        CloseServiceHandle(hSCM);
        return;
    }
}

4 Shut down the service

///@ 关闭服务
void MainWindow::closeService()
{
    // 关闭服务和服务控制管理器的句柄
    CloseServiceHandle(hService);
    CloseServiceHandle(hSCM);
}

5 Start the service

///@ 启动服务
void MainWindow::startService()
{
    if (!StartService(hService, 0, NULL)) {
        qDebug() << "StartService failed with error:" << GetLastError();
    }
}

6 Stop service

///@ 停止服务
void MainWindow::stopService()
{
    SERVICE_STATUS status;
    if (!ControlService(hService, SERVICE_CONTROL_STOP, &status)) {
        qDebug() << "ControlService failed with error:" << GetLastError();
    }
}

7 automatic start

///@ 自动启用服务
void MainWindow::enableService()
{
    enable = true;
    if (!ChangeServiceConfig(
        hService,        // handle of service
        SERVICE_NO_CHANGE, // service type: no change
        enable ? SERVICE_DEMAND_START : SERVICE_DISABLED,
        SERVICE_NO_CHANGE, // error control: no change
        NULL,              // binary path: no change
        NULL,              // load order group: no change
        NULL,              // tag ID: no change
        NULL,              // dependencies: no change
        NULL,              // service start name: no change
        NULL,              // password: no change
        NULL))             // display name: no change
    {
        qDebug() << "ChangeServiceConfig failed with error:" << GetLastError();
    }
}

8 Manual start

///@ 手动启用服务
void MainWindow::manualService()
{
    enable = true;
    if (!ChangeServiceConfig(
        hService,        // handle of service
        SERVICE_NO_CHANGE, // service type: no change
        enable ? SERVICE_AUTO_START : SERVICE_DISABLED, // service start type   SERVICE_DEMAND_START
        SERVICE_NO_CHANGE, // error control: no change
        NULL,              // binary path: no change
        NULL,              // load order group: no change
        NULL,              // tag ID: no change
        NULL,              // dependencies: no change
        NULL,              // service start name: no change
        NULL,              // password: no change
        NULL))             // display name: no change
    {
        qDebug() << "ChangeServiceConfig failed with error:" << GetLastError();
    }
}

9 Inquiry service

void MainWindow::findService()
{
    QSettings servicesSettings("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services", QSettings::NativeFormat);
    QStringList services = servicesSettings.childGroups();

    for (const QString& service : services) {
        printServiceInfo(service);
    }
}
void MainWindow::printServiceInfo(const QString& serviceName)
{
    qDebug() << "服务名称: " << serviceName;    //Service Name
    QSettings serviceSettings("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\" + serviceName, QSettings::NativeFormat);
    QStringList keys = serviceSettings.allKeys();


    if(serviceSettings.value("DisplayName").toString() == "")
        return;

     qDebug() << "显示名称: " << serviceSettings.value("DisplayName").toString();
     qDebug() << "描述: " << serviceSettings.value("Description").toString();
     qDebug() << "映像路径: " << serviceSettings.value("ImagePath").toString();


     QString displayName = QCoreApplication::translate("WalletService", "@%SystemRoot%\\System32\\WalletService.dll,-1000");
     QString description = QCoreApplication::translate("WalletService", "@%SystemRoot%\\System32\\WalletService.dll,-1001");

     qDebug() << "显示名称:" << displayName;
     qDebug() << "描述:" << description;
}

10.h source file

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QDebug>
#include <QSettings>
#include <windows.h>
#include <winsvc.h>
#include <iostream>
#pragma comment(lib, "advapi32.lib")

#define MAX_SERVICE_SIZE 1024 * 64
#define MAX_QUERY_SIZE   1024 * 8

#pragma execution_character_set("utf-8")

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    SC_HANDLE hSCM;
    SC_HANDLE hService;
private:
    Ui::MainWindow *ui;

    bool enable;

    void openService();
    void closeService();
    void findService();
    void printServiceInfo(const QString& serviceName);
    void startService();
    void stopService();
    void newService();
    void deleteService();
    void enableService();
    void manualService();
    void disabledService();
};
#endif // MAINWINDOW_H

Guess you like

Origin blog.csdn.net/qq_37529913/article/details/133901528