关于WMI开发随笔一
今天研究了一下关于WMI对于打印机的操作,目前研究,仅仅研究了网络打印机(即打印机自带网卡)
1、安装打印机端口
2、添加驱动程序
3、添加打印机
4、设置为默认
一、打印机端口添加,使用 WMI的命名空间Win32_TCPIPPrinterPort,需要设置以下几个属性
"Name" = "财务打印端口"
"Protocol"=1
“HostAddress"="192.168.0.139"
”PortNumber"=9100
“SNMPEnabled"=False
示例代码:
Dim connectionOptions As ConnectionOptions = New ConnectionOptions
connectionOptions.Username = "UserName"
connectionOptions.Password = "Password"
connectionOptions.EnablePrivileges = True
connectionOptions.Impersonation = ImpersonationLevel.Impersonate
connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy
Dim managementScope = New ManagementScope(HostPath, connectionOptions)
managementScope.Connect()
Dim Query As ObjectQuery = New ObjectQuery("SELECT * FROM Win32_TCPIPPrinterPort")
Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(managementScope, Query)
For Each mo As ManagementObject In searcher.[Get]()
Dim moType = New PutOptions()
mo.Properties("Name") = "财务打印端口"
mo.Properties("Protocol")=1
mo.Properties(“HostAddress")="192.168.0.139"
mo.Properties(”PortNumber")=9100
mo.Properties(“SNMPEnabled")=False
moType.UseAmendedQualifiers = True
moType.Type = PutType.UpdateOrCreate
mo.Put(moType)
Next
端口搞定。
二、添加驱动程序 这里略过,因为今天添加的驱动程序有两个比较大的问题,1是系统本身自带的驱动,2是其他路径存储的驱动(系统不带驱动),在调试的时候发现有多种错误代码返回:1、1151的错误;2、3758096964的错误;3、87的错误。但总结还是要区分对待驱动程序的类别,一般系统默认带的驱动都比较容易安装,系统默认不带驱动的需要看驱动类型,有的驱动还是比较麻烦的,很容易出现以上三种甚至更多的错误代码;
三、添加打印机,使用 WMI的命名空间Win32_Printer,需要设置以下几个属性
"DriverName", "HP LaserJet 8150 Series PS"
"PortName", "财务打印端口"
"DeviceID", "财务打印机"
"Location", "财务部门前打印机"
"Priority", 2
代码就不再赘述,雷同添加打印机端口的代码,只要修改相应属性即可。
四、设置打印机为默认时,出现了错误,经过排错还是没有找到解决办法---暂时搁置。
首先是调用 Win32_Printer 命名空间的 SetDefaultPrinter 方法时,遇到错误: Not supported
行号: mo.InvokeMethod("SetDefaultPrinter", Nothing)
示例代码:
Dim connectionOptions As ConnectionOptions = New ConnectionOptions
connectionOptions.Username = "UserName"
connectionOptions.Password = "Password"
connectionOptions.EnablePrivileges = True
connectionOptions.Impersonation = ImpersonationLevel.Impersonate
connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy
Dim managementScope = New ManagementScope(HostPath, connectionOptions)
managementScope.Connect()
Dim Query As ObjectQuery = New ObjectQuery("SELECT * FROM Win32_TCPIPPrinterPort")
Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher(managementScope, Query)
For Each mo As ManagementObject In searcher.[Get]()
If mo.Properties("DeviceID").Value.ToString = "财务打印机" Then
mo.InvokeMethod("SetDefaultPrinter", Nothing)
''系统返回“不支持”
End If
Next
如果哪位师兄有可以参考的代码,望不吝赐教。