I need to get the default printer name. I\'ll be using C# but I suspect this is more of a framework question and isn\'t language specific.
Another approach is using WMI (you'll need to add a reference to the System.Management assembly):
public static string GetDefaultPrinterName()
{
var query = new ObjectQuery("SELECT * FROM Win32_Printer");
var searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject mo in searcher.Get())
{
if (((bool?) mo["Default"]) ?? false)
{
return mo["Name"] as string;
}
}
return null;
}
PrintDialog
object.PrinterName
blank. this will cause the windows object to return the defualt printer nameCode:
Try
Dim _printDialog As New System.Windows.Forms.PrintDialog
xPrinterName = _printDialog.PrinterSettings.PrinterName '= "set as Default printer"
Catch ex As Exception
System.Windows.Forms.MessageBox.Show("could not printed Label.", "Print Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Try also this example
PrinterSettings printerName = new PrinterSettings();
string defaultPrinter;
defaultPrinter = printerName.PrinterName;
If you just want the printer name no advantage at all. But WMI is capable of returning a whole bunch of other printer properties:
using System;
using System.Management;
namespace Test
{
class Program
{
static void Main(string[] args)
{
ObjectQuery query = new ObjectQuery(
"Select * From Win32_Printer " +
"Where Default = True");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(query);
foreach (ManagementObject mo in searcher.Get())
{
Console.WriteLine(mo["Name"] + "\n");
foreach (PropertyData p in mo.Properties)
{
Console.WriteLine(p.Name );
}
}
}
}
}
and not just printers. If you are interested in any kind of computer related data, chances are you can get it with WMI. WQL (the WMI version of SQL) is also one of its advantages.
The easiest way I found is to create a new PrinterSettings
object. It starts with all default values, so you can check its Name property to get the name of the default printer.
PrinterSettings
is in System.Drawing.dll in the namespace System.Drawing.Printing
.
PrinterSettings settings = new PrinterSettings();
Console.WriteLine(settings.PrinterName);
Alternatively, you could maybe use the static PrinterSettings.InstalledPrinters
method to get a list of all printer names, then set the PrinterName property and check the IsDefaultPrinter. I haven't tried this, but the documentation seems to suggest it won't work. Apparently IsDefaultPrinter is only true when PrinterName is not explicitly set.
I use always in this case the System.Printing.LocalPrintServer, which makes also possible to obtain whether the printer is local, network or fax.
string defaultPrinter;
using(var printServer = new LocalPrintServer()) {
defaultPrinter = printServer.DefaultPrintQueue.FullName);
}
or using a static method GetDefaultPrintQueue
LocalPrintServer.GetDefaultPrintQueue().FullName