要使用 PdhAddCounter 函数获取指定进程的网络发送和接收速率,需要先获取进程的实例 ID,然后构造对应的性能计数器路径。

以下是获取指定进程网络发送和接收速率的示例代码:

#include <windows.h>
#include <pdh.h>
#include <pdhmsg.h>

#pragma comment(lib, "pdh.lib")

int main()
{
    PDH_STATUS pdhStatus;
    HQUERY hQuery;
    HCOUNTER hCounterSent, hCounterReceived;
    PDH_FMT_COUNTERVALUE counterValueSent, counterValueReceived;

    // 创建查询对象
    pdhStatus = PdhOpenQuery(NULL, 0, &hQuery);
    if (pdhStatus != ERROR_SUCCESS) {
        printf("PdhOpenQuery failed with 0x%x\n", pdhStatus);
        return 1;
    }

    // 添加网络发送速率计数器
    pdhStatus = PdhAddCounter(hQuery, L"\Process(<进程名>)\IO Write Bytes/sec", 0, &hCounterSent);
    if (pdhStatus != ERROR_SUCCESS) {
        printf("PdhAddCounter for Sent failed with 0x%x\n", pdhStatus);
        return 1;
    }

    // 添加网络接收速率计数器
    pdhStatus = PdhAddCounter(hQuery, L"\Process(<进程名>)\IO Read Bytes/sec", 0, &hCounterReceived);
    if (pdhStatus != ERROR_SUCCESS) {
        printf("PdhAddCounter for Received failed with 0x%x\n", pdhStatus);
        return 1;
    }

    // 收集计数器数据
    pdhStatus = PdhCollectQueryData(hQuery);
    if (pdhStatus != ERROR_SUCCESS) {
        printf("PdhCollectQueryData failed with 0x%x\n", pdhStatus);
        return 1;
    }

    // 获取网络发送速率
    pdhStatus = PdhGetFormattedCounterValue(hCounterSent, PDH_FMT_DOUBLE, NULL, &counterValueSent);
    if (pdhStatus != ERROR_SUCCESS) {
        printf("PdhGetFormattedCounterValue for Sent failed with 0x%x\n", pdhStatus);
        return 1;
    }

    // 获取网络接收速率
    pdhStatus = PdhGetFormattedCounterValue(hCounterReceived, PDH_FMT_DOUBLE, NULL, &counterValueReceived);
    if (pdhStatus != ERROR_SUCCESS) {
        printf("PdhGetFormattedCounterValue for Received failed with 0x%x\n", pdhStatus);
        return 1;
    }

    // 输出结果
    printf("Sent: %.2f bytes/sec\n", counterValueSent.doubleValue);
    printf("Received: %.2f bytes/sec\n", counterValueReceived.doubleValue);

    // 关闭查询对象
    PdhCloseQuery(hQuery);

    return 0;
}

注意替换代码中的<进程名>为要监测的进程名称。

C++ 使用 PdhAddCounter 获取指定进程网络发送和接收速率

原文地址: https://www.cveoy.top/t/topic/fRkr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录