使用 C#(系统范围)获取打印页数

Get number of printed pages using C# (system-wide)

我已经搞了将近 2 天了,我什么都没完成!!
我被指派编写一个程序来计算 windows OS.
上打印的页数 据我所知,我需要拦截打印事件并在内部对其进行计数。我应该使用 FindFirstPrinterChangeNotificationFindNextPrinterChangeNotification.

我已经分配了一个具有以下签名的回调函数 PrinterNotifyWaitCallback,它会在打印事件发生时触发 多次

 public void PrinterNotifyWaitCallback(Object state, bool timedOut) { ... }

问题:

我知道为什么打印事件会触发PrinterNotifyWaitCallback多次但是我无法区分实际情况在那些多个回调中打印回调事件,这显然与 Object state 有关,但关于如何实现我的 objective 的文档为零,它正在计算打印页数。

问题:

  1. 如何区分 PrinterNotifyWaitCallback 的实际打印回调以计算总打印页数 系统范围?
  2. 还有其他更好的方法来完成任务吗?

通过WMI大致找到了解决办法。对于它的价值,我想出了以下方法来计算打印页数。

lock (this._printStatusLast)
{
    // make a query to OS
    // TODO: make the printers exclude from counting in below query (defined by admin)
    ManagementObjectCollection pmoc = new ManagementObjectSearcher("SELECT Name, NotReadyErrors, OutofPaperErrors, TotalJobsPrinted, TotalPagesPrinted FROM Win32_PerfRawData_Spooler_PrintQueue").Get();
    Dictionary<String, PrintDetail> phs = new Dictionary<string, PrintDetail>();
    foreach (ManagementObject mo in pmoc)
    {
        // do not count everything twice!! (this is needed to for future developments on excluding printers from getting count)
        if (mo["name"].ToString().ToLower() == "_total") continue;
        PrintDetail pd = new PrintDetail();
        foreach (PropertyData prop in mo.Properties)
        {
            if (prop.Name.ToLower() == "name") continue;
            pd[prop.Name] = (UInt32)prop.Value;
        }
        phs.Add(mo["name"].ToString(), pd);
    }
    UInt32 count = 0;
    // foreach category
    foreach (var _key in phs.Keys.ToArray<String>())
    {
        // do not count if there where any errors
        if (phs[_key].HasError) continue;
        count += phs[_key].TotalPagesPrinted;
    }
    this.txtPrint.Text = count.ToString();
    this._printStatusLast = new Dictionary<string, PrintDetail>(phs);
}