使用 PdhAddCounter 函数获取指定进程的网络发送和接收速率,需要先获取进程的实例 ID,然后使用网络接口实例 ID 和计数器路径构建计数器路径字符串,最后使用 PdhAddCounter 函数添加计数器。

以下是一个示例代码:

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

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

int main()
{
    PDH_STATUS pdhStatus;
    HQUERY hQuery;
    HCOUNTER hCounterSent, hCounterReceived;
    DWORD dwProcessId = 1234; // 替换为要监视的进程ID

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

    // 获取进程实例ID
    WCHAR szInstanceName[MAX_PATH];
    swprintf_s(szInstanceName, L"\Process(%u)", dwProcessId);

    // 构建计数器路径字符串
    WCHAR szCounterPathSent[MAX_PATH];
    swprintf_s(szCounterPathSent, L"\Network Interface(*)\Bytes Sent/sec");
    WCHAR szCounterPathReceived[MAX_PATH];
    swprintf_s(szCounterPathReceived, L"\Network Interface(*)\Bytes Received/sec");

    // 添加计数器
    pdhStatus = PdhAddCounter(hQuery, szCounterPathSent, 0, &hCounterSent);
    if (pdhStatus != ERROR_SUCCESS) {
        printf("PdhAddCounter failed with 0x%x\n", pdhStatus);
        return 1;
    }

    pdhStatus = PdhAddCounter(hQuery, szCounterPathReceived, 0, &hCounterReceived);
    if (pdhStatus != ERROR_SUCCESS) {
        printf("PdhAddCounter 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;
    }

    // 获取计数器值
    PDH_FMT_COUNTERVALUE counterValueSent, counterValueReceived;
    pdhStatus = PdhGetFormattedCounterValue(hCounterSent, PDH_FMT_DOUBLE, NULL, &counterValueSent);
    if (pdhStatus != ERROR_SUCCESS) {
        printf("PdhGetFormattedCounterValue failed with 0x%x\n", pdhStatus);
        return 1;
    }

    pdhStatus = PdhGetFormattedCounterValue(hCounterReceived, PDH_FMT_DOUBLE, NULL, &counterValueReceived);
    if (pdhStatus != ERROR_SUCCESS) {
        printf("PdhGetFormattedCounterValue failed with 0x%x\n", pdhStatus);
        return 1;
    }

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

    // 关闭查询
    PdhCloseQuery(hQuery);

    return 0;
}

请注意,该示例代码中的进程ID需要替换为要监视的实际进程ID。另外,需要在代码中添加错误处理和释放资源的逻辑。

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

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

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