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.
-
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 namespaceSystem.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.From OwenP -
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; }
From Nathan Baulch -
What's the advantage of using WMI vs the PrinterSettings object?
From Kevin Gale -
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.
From Uros Calakovic -
1st create an instance of the printdialog object. then Call the print dialog object and leave the printername blank. this will cause the windows object to return the defualt printer name, write this to a string and use it as the printer name when you call the print procedure
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
0 comments:
Post a Comment