每次 Windows 在執行列印動作時能夠在事件檢視器中產生紀錄
可以透過 C# 取得這些紀錄
但是預設情況下此紀錄是關閉的需要先開啟才能進行記錄

using System.Diagnostics.Eventing.Reader;

var elConfig = new EventLogConfiguration("Microsoft-Windows-PrintService/Operational", new EventLogSession());
if (!elConfig.IsEnabled)
{
    elConfig.IsEnabled = true;
    elConfig.SaveChanges();
}

若無開啟則需要先開啟才能進行紀錄

var query = "*[System/EventID=307]";
var elQuery = new EventLogQuery("Microsoft-Windows-PrintService/Operational", PathType.LogName, query);
var elReader = new EventLogReader(elQuery);

for (EventRecord eventInstance = elReader.ReadEvent(); eventInstance != null; eventInstance = elReader.ReadEvent())
{
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(eventInstance.ToXml());

        var content = new PrinterLogView
        {
            Time = DateTime.SpecifyKind(eventInstance.TimeCreated.Value, DateTimeKind.Local).ToString("o"),
            User = GetPrinterEventData(doc,"Param3"),
            Size = GetPrinterEventData(doc, "Param7"),
            Pages = GetPrinterEventData(doc, "Param8"),
            Printer = GetPrinterEventData(doc, "Param5"),
            Path = GetPrinterEventData(doc, "Param6")
        };    
}

紀錄代碼 307 表示列印成功的紀錄
讀取 XML 內容可以知道列印的資訊
包含檔案大小、路徑、頁數、印表機名稱等等

分類於:

標籤:

, ,