Qt监控后台服务运行状态

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMap>
#include <QTimer>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    void getAllAppPidList(QMap<QString, qint64> &app_pid);
    void OpenServiceManager();
private slots:
    void scanTable();

    void on_pushButton_add_progress_clicked();

    void on_pushButton_add_service_clicked();

private:
    Ui::MainWindow *ui;
    QTimer* scanTimer;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include <windows.h>// for OpenService
#include <tlhelp32.h>// for CreateToolhelp32Snapshot
#include <Psapi.h>   // for GetModuleFileNameEx
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
/*
 *
 * =================================================================
 * !!!!!!!!!!!!!本程序需要管理员身份运行!!!!!!!!!!!!!!!
 * =================================================================
 *
 * */

//使用带bom的UTF8文件格式,在Tools-Options-Text Editor-Behavior-File Encoding-UTF-8 BOM:Add If Emcoding Is UTF-8
#pragma execution_character_set("utf-8")

SC_HANDLE hSCM;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    scanTimer = new QTimer(this);
    connect( scanTimer, SIGNAL(timeout()), SLOT(scanTable()) );
    scanTimer->start( 10 );  // for 100fps

    OpenServiceManager();
}

MainWindow::~MainWindow()
{
    delete ui;
    CloseServiceHandle(hSCM);
}

void MainWindow::scanTable()
{
    //进程
    for(int row=0; row<ui->tableWidget_progress->rowCount(); row++)
        for(int col=0; col<ui->tableWidget_progress->columnCount();col++)
        {
            QTableWidgetItem* item = ui->tableWidget_progress->item(row,col);
            if(item!=NULL)
            {
                QString app=item->text();
            }
        }

    //检测服务是否在运行
    if(hSCM)
    {
        for(int row=0; row<ui->tableWidget_service->rowCount(); row++)
            for(int col=0; col<ui->tableWidget_service->columnCount();col++)
            {
                QTableWidgetItem* item = ui->tableWidget_service->item(row,col);
                if(item!=NULL)
                {
                    QString serviceName=item->text();
                    SC_HANDLE hService = ::OpenService( hSCM, serviceName.toStdWString().data(), SERVICE_ALL_ACCESS );
                    if(hService)
                    {
                        SERVICE_STATUS ssStatus;
                        QueryServiceStatus(hService,&ssStatus);//查看该Service的状态
                        if(ssStatus.dwCurrentState==SERVICE_STOPPED)
                        {
                            ::StartService( hService, 0, NULL );
                            ui->textEdit->append("StartService "+serviceName);
                        }
                        else if(ssStatus.dwCurrentState==SERVICE_RUNNING)
                        {
                            item->setBackground(Qt::green);
                        }
                        CloseServiceHandle(hService);
                    }
                    else
                    {
                        //ui->textEdit->append("OpenService Failed  "+serviceName);
                        item->setBackground(Qt::red);
                    }
                }
            }
    }
}

void MainWindow::OpenServiceManager()
{
    /*
     *
     *
     * 以下服务相关操作需要管理员权限
     *
     *
     *
     * */
    hSCM = ::OpenSCManager(NULL, // local machine
                           NULL, // ServicesActive database
                           SC_MANAGER_ALL_ACCESS); // full access
    if (hSCM) {
        //hService = ::OpenService( hSCM, QString("STEPVR_MMAP_SERVICE").toStdWString().data(), SERVICE_ALL_ACCESS );
        //if(hService==NULL)
        //    ui->textEdit->append("OpenService Failed");
    }
    else
    {
        qDebug()<<"OpenSCManager Fail"<<GetLastError();
        ui->textEdit->append("OpenSCManager Failed");
    }
}

// 根据进程号获取exe所在文件绝对路径
/*QString GetPathByProcessID(DWORD pid)
{
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    if (!hProcess)
    {
        //QMessageBox::warning(NULL,"GetPathByProcessID","无权访问该进程");
        return "";
    }
    WCHAR filePath[MAX_PATH];
    DWORD ret= GetModuleFileNameEx(hProcess, NULL, filePath, MAX_PATH) ;
    QString file = QString::fromStdWString( filePath );
    //QMessageBox::warning(NULL,"GetPathByProcessID ret=", QString::number(ret)+":"+file);
    CloseHandle(hProcess);
    return ret==0?"":file;
}

// 获取机器上正在运行的全部exe
void MainWindow::getAllAppPidList(QMap<QString, qint64> &app_pid)
{
    app_pid.clear();
    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(pe32);
    HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    if(hProcessSnap == INVALID_HANDLE_VALUE)
    {
        //warningLabel->setText("CreateToolhelp32Snapshot调用失败");
        return ;
    }
    BOOL bMore = Process32First(hProcessSnap,&pe32);
    while(bMore)
    {
        //printf("进程名称:%s\n",pe32.szExeFile);
        //printf("进程ID:%u\n\n",pe32.th32ProcessID);

        QString exeName = (QString::fromUtf16(reinterpret_cast<const unsigned short *>(pe32.szExeFile)));
        QString exePath = GetPathByProcessID( pe32.th32ProcessID );
        exePath = FORMAT_PATH( exePath );
        //qDebug()<<exePath.toLower();
        if( exePath.isEmpty() )
        {
            //warningLabel->setText("获取进程 " + exeName + " 路径失败");
        }
        else
        {
            app_pid[exePath] = pe32.th32ProcessID;
        }

        bMore = Process32Next(hProcessSnap,&pe32);
    }
    CloseHandle(hProcessSnap);
}*/

void MainWindow::on_pushButton_add_progress_clicked()
{
    ui->tableWidget_progress->insertRow(ui->tableWidget_progress->rowCount());
}

void MainWindow::on_pushButton_add_service_clicked()
{
    ui->tableWidget_service->insertRow(ui->tableWidget_service->rowCount());
}

 

posted @ 2017-07-10 11:38  酷熊  阅读(3736)  评论(1编辑  收藏  举报