使用 PdhAddCounter 函数获取特定进程的网络发送速率流量,需要先获取该进程的实例索引。具体步骤如下:

  1. 使用 PdhOpenQuery 函数创建性能数据查询对象。
  2. 使用 PdhAddCounter 函数添加网络接口实例计数器(例如:'\Network Interface(*)\Bytes Sent/sec')。
  3. 使用 PdhCollectQueryData 函数收集性能数据。
  4. 使用 PdhGetFormattedCounterValue 函数获取特定进程的网络发送速率流量。

以下是一个示例代码:

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

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

int main()
{
    PDH_STATUS pdhStatus;
    HQUERY hQuery;
    HCOUNTER hCounter;
    PDH_FMT_COUNTERVALUE counterValue;

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

    // 添加网络接口实例计数器
    pdhStatus = PdhAddCounter(hQuery, "\\Network Interface(*)\\Bytes Sent/sec", 0, &hCounter);
    if (pdhStatus != ERROR_SUCCESS)
    {
        printf("PdhAddCounter failed with 0x%x\n", pdhStatus);
        PdhCloseQuery(hQuery);
        return 1;
    }

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

    // 获取特定进程的网络发送速率流量
    pdhStatus = PdhGetFormattedCounterValue(hCounter, PDH_FMT_DOUBLE, NULL, &counterValue);
    if (pdhStatus != ERROR_SUCCESS)
    {
        printf("PdhGetFormattedCounterValue failed with 0x%x\n", pdhStatus);
        PdhCloseQuery(hQuery);
        return 1;
    }

    printf("Network Bytes Sent/sec: %.2f\n", counterValue.doubleValue);

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

    return 0;
}

请注意,上述示例代码中的网络接口实例计数器是一个通配符,可以匹配所有的网络接口。如果要获取特定进程的网络发送速率流量,需要将通配符替换为具体的网络接口实例名称。可以使用 PdhEnumObjectItems 函数列出可用的网络接口实例名称。

C++ 使用 PdhAddCounter 获取特定进程网络发送速率

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

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