get the default printer

  • Thread starter Thread starter Pablo
  • Start date Start date
P

Pablo

Friends,

how can i get the name of the default printer??. I'm
working with winforms. VB,C#, nevermind.

Thanks a lot
Pablo
 
Pablo, You can use WMI to get and set the default printer.
Example follows.

----
Ionic Shade
Microsoft Developer Division


// Printer.cs
//
// sets the default printer using WMI
//
// references:
//
http://msdn.microsoft.com/library/e...aultprinter_method_in_class_win32_printer.asp
//
// Fri, 19 Sep 2003 14:14
//


public class PrinterTest {

public static void Main(string[] args) {

string PrinterToSelect= null;
if (args.Length>0) {
if (!(args[0].StartsWith("-")))
PrinterToSelect= args[0];
else {
System.Console.WriteLine("\nThis utility lists the configured
printers, and optionally selects\na new default printer.\n");
System.Console.WriteLine("usage: Printer [<name of printer to
select as default>]");
return ;
}
}


// Get the list of configured printers:
string strQuery= "SELECT * FROM Win32_Printer";

System.Console.WriteLine("WMI Query: '{0}'", strQuery);

System.Console.WriteLine("==============================================");
System.Management.ObjectQuery oq = new
System.Management.ObjectQuery(strQuery);

System.Management.ManagementObjectSearcher query1 = new
System.Management.ManagementObjectSearcher(oq);
System.Management.ManagementObjectCollection queryCollection1 =
query1.Get();
System.Management.ManagementObject newDefault= null;

foreach( System.Management.ManagementObject mo in queryCollection1 ) {
System.Management.PropertyDataCollection pdc = mo.Properties;
System.Console.WriteLine("'{0}'", mo["Name"]);
if ((bool)mo["Local"])
System.Console.WriteLine(" A local printer");
else if ((bool)mo["Network"])
System.Console.WriteLine(" a network printer located at: {0}",
mo["Location"]);

// if you want to display all properties of every printer
// foreach (System.Management.PropertyData pd in pdc) {
// System.Console.WriteLine(" {0:12} : {1}", pd.Name,
mo[pd.Name]);
// }


if ((bool)mo["Default"]) {
System.Console.WriteLine(" THIS IS THE DEFAULT PRINTER");
}
else if (mo["Name"].ToString().Trim()==PrinterToSelect)
newDefault= mo; // store for later

System.Console.WriteLine("");
}


if (newDefault!=null) {
System.Console.WriteLine("\nRESETTING THE DEFAULT PRINTER to '{0}'",
newDefault["Name"]);

//Execute the method
System.Management.ManagementBaseObject outParams =
newDefault.InvokeMethod ("SetDefaultPrinter", null, null);

//Display results
//Note: The return code of the method is provided in the "returnValue"
property of the outParams object
System.Console.WriteLine("SetDefaultPrinter() returned: " +
outParams["returnValue"]);
}

}
}
 
Back
Top