I am able to get print job informations from Win32_PrintJob
by using WMI and ManagementEventWatcher
but I cannot seem to find the printer name. I also looked to this Win32_PrintJob documentation and the closest thing to printer name is DriverName
property, but it is the printer driver name, not the printer name as displayed in the Control Panel's Devices and Printers.
So, as stated in the title, how can I get the printer name from print job from Win32_PrintJob
?
This is my partial codes so far to get the print job:
public void PrintHelperInstance_OnPrintJobChange(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject objProps = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
string jobName = objProps["Document"].ToString();
if (jobName == "Test Print Form")
{
if (!IsFoundPrintJob)
{
IsFoundPrintJob = true;
}
CurrentJobStatus = (string)objProps["JobStatus"];
if (CurrentJobStatus != PreviousJobStatus)
{
uint jobId = (uint)objProps["JobId"];
string jobPrinter = (string)objProps["DriverName"];
string jobHost = (string)objProps["HostPrintQueue"];
string jobStatus = (string)objProps["JobStatus"];
PreviousJobStatus = CurrentJobStatus;
}
}
}
You can use this code :
// produce wmi query object
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Printer");
// produce search object
ManagementObjectSearcher search = new ManagementObjectSearcher(query);
// retrieve result collection
ManagementObjectCollection result = search.Get();
// iterate through all printers
foreach(ManagementObject obj in result)
{
// now create your temp printer class
Dictionary<string, object> printerObj = new Dictionary<string, object>();
if(obj.GetPropertyValue("Local").ToString().Equals("true"))
{
printerObj.Add("isLocal", true);
printerObj.Add("name", obj.GetPropertyValue("name").ToString());
}
else
{
printerObj.Add("isLocal", false);
printerObj.Add("serverName", obj.GetPropertyValue("ServerName").ToString());
printerObj.Add("shareName", obj.GetPropertyValue("ShareName").ToString());
}
// create real printer object
PrintServer srv = ((bool)printerObj["isLocal")) ? new LocalPrintServer() : new PrintServer((string)printerObj["serverName"]);
PrintQueue queue = srv.GetPrintQueue(((bool)printerObj["isLocal")) ? (string)printerObj["name"] : (string)printerObj["shareName"];
foreach(var job in queue.GetPrintJobInfoCollection())
{
// check job info and if it matches, return printer name;
}
}