首先,IsValid的檢查PrinterName的財產的價值,看它是否是一個有效的值,如果沒有連接打印機。
其次,在WPF中很容易做到這一點;
var defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
if (!defaultPrintQueue.IsNotAvailable)
{
//print stuff
}
檢查docs更多細節: 在的WinForms,它有點困難,但你可以使用WMI。參考System.Management.dll並添加以下using語句:
using System;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Management;
要獲得所有默認打印機:
注意下面的代碼很可能是依賴於操作系統在一定程度上。檢查MSDN文檔..
var printerSearcher =
new ManagementObjectSearcher(
"SELECT * FROM Win32_Printer where Default = true"
);
return printerSearcher.Get();
的WMI documentation for the printer對象介紹了一些有用的結構,我們可以看一下; PrinterStatus和WorkOffline。我們可以利用這些寫一個實用工具類,以檢查打印機的可用性,同時檢查其WorkOffline狀態......
public static class PrinterUtility
{
public static bool IsOnline(this ManagementBaseObject printer)
{
var status = printer["PrinterStatus"];
var workOffline = (bool)printer["WorkOffline"];
if (workOffline) return false;
int statusAsInteger = Int32.Parse(status.ToString());
switch (statusAsInteger)
{
case 3: //Idle
case 4: //Printing
case 5: //Warming up
case 6: //Stopped printing
return true;
default:
return false;
}
}
public static ManagementObjectCollection GetDefaultPrinters()
{
var printerSearcher =
new ManagementObjectSearcher(
"SELECT * FROM Win32_Printer where Default = true"
);
return printerSearcher.Get();
}
}
現在你可以用標準的WinForms System.Drawing.Printing代碼結合本:
//in a function, far far away from any button click handler :P
foreach(var printer in PrinterUtility.GetDefaultPrinters())
{
if (printer.IsOnline())
{
var pDoc = new PrintDocument(); //or get from PrintDialog
pDoc.PrinterSettings.PrinterName = printer["Name"].ToString();
if (pDoc.PrinterSettings.IsValid) //just check WMI didn't tell fibs about the name
{
//do printy things
}
}
}
希望這有助於
我會盡快嘗試。 – Valentein 2010-04-15 18:41:20