Reputation: 81
I want to be able to do the equivalent of the following in c#:
I have managed to get a ManagementObject for a named printer and tried to call:
mObj.SetPropertyValue("PortName","COM12:");
On the ManagementObject for that Printer - whch inherits from ManagementBaseObject.
However, this piece of code didn't do anything to the Printer Settings.
I suspect that I will need to use P/Invoke on the appropriate library but after a lot of searching I cannot find the library or a tutorial for how to do this from c#.
Any help would be much appreciated.
Upvotes: 3
Views: 4469
Reputation: 81
Found the answer on an obscure part of the internet:
public static void SetPrinterPort(string printerName, string portName)
{
var oManagementScope = new ManagementScope(ManagementPath.DefaultPath);
oManagementScope.Connect();
SelectQuery oSelectQuery = new SelectQuery();
oSelectQuery.QueryString = @"SELECT * FROM Win32_Printer
WHERE Name = '" + printerName.Replace("\\", "\\\\") + "'";
ManagementObjectSearcher oObjectSearcher =
new ManagementObjectSearcher(oManagementScope, @oSelectQuery);
ManagementObjectCollection oObjectCollection = oObjectSearcher.Get();
foreach (ManagementObject oItem in oObjectCollection)
{
oItem.Properties["PortName"].Value = portName;
oItem.Put();
}
}
I am pretty sure that the last part is all you need to set properties on any Management Object. It was driving me nuts that I could see that the Win32 API said the property I wanted to set was read/write but nowhere seemed to have the code for setting it.
Well now we know! :-)
I hope this is useful for someone.
Upvotes: 5