概要
Windows のデフォルトプリンターを取得します。同時にデバイスに登録されているプリンターの一覧も取得します。
印刷関連のメソッドで、現在の印刷環境を判断するのにご使用ください。
機能
- Windows OSに登録されているプリンターを一覧で取得します。
- 一覧の1番目にデフォルトのプリンター名を返します。
- 一覧の2番目以降に他のプリンター名を返します。
- 一覧の1番目「strPrinterName(0)」が空 ""の時はプリンターは一件も登録されていません。
形式
1 |
Boolean = GetDefPrinterName_All(ByRef strPrinterName() As String) |
引数
- 第一引数 ( string strPrinterName() ) :
プリンター名の一覧が返されます。
動的配列なので配列のサイズは指定しません。関数側でReDim で設定されて返されます。1Dim strPrinterName() As String
戻り値
- True:エラー無し
- False:実行エラー
サンプル
デフォルトプリンター名をstrPrinterName(0)に返します。それ以外はstrPrinterName(1)以降の配列に返します。
Download:sample-GetAllPrinters.xls
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
Option Explicit Sub test_Main_nnn2GetAllPrinters() Dim strPrinterName() As String Dim bRet As Boolean bRet = nnn2GetAllPrinters(strPrinterName) Dim i As Long For i = 0 To UBound(strPrinterName) If i = 0 Then 'Default Printer Debug.Print i & " = " & strPrinterName(i) _ & " (Default Printer)" Else Debug.Print i & " = " & strPrinterName(i) End If Next i Debug.Print "Cound = " & UBound(strPrinterName, 1) + 1 End Sub '====================================================================== ' ' 名称 :OSのプリンターを全て取得 ' 機能 :OSのプリンターを取得して、strPrinterName()配列に返す。 ' strPrinterName(0)には「通常使うプリンター」がセットされる。 ' strPrinterName(1)以上にそれ以外はプリンターがセットされる。 ' バージョン:1.0 ' 作成日 :2017/08/19 初版 ' URL :http://pdf-file.nnn2.com/?p=1012 ' '====================================================================== Private Function nnn2GetAllPrinters( _ ByRef strPrinterName() As String) As Boolean nnn2GetAllPrinters = True On Error GoTo Err_nnn2GetAllPrinters: ReDim strPrinterName(10) As String Dim varWMIService As Variant Dim varPS As Variant Dim objPrinter As Object Dim i As Long i = 0 strPrinterName(0) = "" strPrinterName(1) = "" Set varWMIService = CreateObject("winmgmts:{impersonationLevel=impersonate}!¥¥.¥root¥cimv2") Set varPS = varWMIService.ExecQuery("Select * from Win32_Printer") For Each objPrinter In varPS If objPrinter.Default Then '通常使うプリンターを取得 strPrinterName(0) = objPrinter.Caption Else i = i + 1 strPrinterName(i) = objPrinter.Caption End If Next ReDim Preserve strPrinterName(i) As String Exit Function Err_nnn2GetAllPrinters: MsgBox "nnn2GetAllPrinters " & vbCrLf & _ Err.Description, vbCritical, "Runtime Error" nnn2GetAllPrinters = False End Function |
実行結果
1 2 3 4 5 6 |
0 = Adobe PDF (Default Printer) 1 = Microsoft XPS Document Writer 2 = Microsoft Print to PDF 3 = Fax 4 = ¥¥AMD-PC¥Brother DCP-J957N Printer Cound = 5 |
- 配列の1番目(添字=0)にデフォルトのプリンタ名が返されます。
- 「¥¥AMD-PC¥」とあるのはネットワークプリンターです。
- プリンター名の数は Ubound(strPrinterName,1)+1 の結果です。
参照
< サンプル一覧 >