Friday, August 12, 2011

How to set the default printer in IronRuby

Figured I'd convert a work script from Ruby to IronRuby, since its managing a Windows application.

1. Add the following to the top of your script...

require 'mscorlib'
require 'System'
require 'System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
* Added: you can apparently change the "Version" to 4.0.0.0 if you have .NET 4.0 loaded.

2. Here's the function I wrote to set the default printer
# Set default printer
def setDefaultPrinter(defaultPrinterName)
  Printer = System::Management::ManagementObject
  printer = Printer.new("win32_printer.DeviceId='" + defaultPrinterName + "'")
  printer.InvokeMethod("SetDefaultPrinter", nil)
end
References

* "Getting Started with IronRuby"
* System.Management.ManagementObject class on MSDN
* CodeProject article that uses the InvokeMethod for setting the default printer
"Query WMI with IronRuby"

No comments:

Post a Comment