4

プリンタが接続されているポート (Ne01:、Ne02:、Ne99: など) を検出するにはどうすればよいですか?

ここ BigCorp のコンピュータ (WinXP) には、「Adobe PDF」という名前の仮想プリンタを提供する Adob​​e Acrobat (バージョン 7.0 Pro) がインストールされています。マクロの記録中に Excel (2003) ワークブックを pdf に印刷する場合、プリンターの完全な名前は「Adobe PDF on Nexx:」です。ここで、xx は 2 桁の数字です。使用するコンピューターによって異なります。

私は、一連のスプレッドシートを開く Excel.Interop を使用して C# コンソール アプリを作成しました (他の人がこのような地獄への道を歩み始めることを強く思いとどまらせます)。それぞれでマクロを実行し、保存し、PDFとして印刷してから、PDFを共有ドライブのレポートフォルダーに移動します。

私が直面している問題は、Acrobat をインストールするたびに、PDF プリンターのポート番号がランダムに選択されるように見えることです...そして、それを取得する方法がわかりません。

これまでのところ、Win32_Printer クラスを次のように使用してみました

var searcher = new ManagementObjectSearcher( @"SELECT * FROM Win32_Printer" );
foreach ( ManagementObject printer in searcher.Get() )
{
   if ( Regex.IsMatch( printer["Name"].ToString(), @"(adobe|pdf)", RegexOptions.IgnoreCase ) )
   {
       //printer["Name"];    => "Adobe PDF"
       //printer["PortName"] => "my documents/*.pdf"
       foreach ( PropertyData pd in printer.Properties )
       {
           Console.WriteLine(string.Format("{0}, {1}", pd.Name, pd.Value));
       }
           break;
      }
}

System.Drawing.Printing クラスも調べてみました。PrinterSettings.InstalledPrintersは、プリンターの名前「Adobe PDF」を提供しますが、ポート情報を取得する方法がわかりません。

「Adobe PDF」だけをExcel相互運用のPrintOut()メソッドに渡すと、「ドキュメントの印刷に失敗しました」というエラーが表示されて失敗することがあります...理由がわかりません。

ハードコードされた「Adobe PDF on Ne0x:」を適切な x 値で渡すと、毎回動作します。

考えられるすべてのバリエーションを試すと、Excel はデフォルトのプリンターに印刷されます。デフォルトのプリンターを変更するオプションがない (セキュリティ ポリシーの制限)

プリンター ポートを正しくプルするコードを教えてもらえますか?

4

3 に答える 3

5

これが私がやったことです

using Microsoft.Win32;
...

        var devices = Registry.CurrentUser.OpenSubKey( @"Software\Microsoft\Windows NT\CurrentVersion\Devices" ); //Read-accessible even when using a locked-down account
        string printerName = "Adobe PDF";

        try
        {

            foreach ( string name in devices.GetValueNames() )
            {
                if ( Regex.IsMatch( name, printerName, RegexOptions.IgnoreCase ) )
                {
                    var value = (String)devices.GetValue( name );
                    var port = Regex.Match( value, @"(Ne\d+:)", RegexOptions.IgnoreCase ).Value;  
                    return printerName + " on " + port;
                }
            }
        }
        catch
        {
            throw;
        }
于 2011-04-28T16:35:14.113 に答える
1

前回 Acrobat を使用したときは、常に LPT1 にインストールされていたため、問題を回避できました。しかし、レジストリをうろつく必要があると思いますHKCU\Software\Microsoft\Windows NT\CurrentVersion\Devices

于 2011-03-24T20:39:10.960 に答える
0

レジストリを照会する必要があることを発見したように、これは私が[in VBA]を使用した方法であり、 Chip Pearson の優れた Excel サイトから取得しました。

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' modListPrinters
' By Chip Pearson, chip@cpearson.com  www.cpearson.com
' Created 22-Sept-2012
' This provides a function named GetPrinterFullNames that
' returns a String array, each element of which is the name
' of a printer installed on the machine.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Const HKEY_CURRENT_USER As Long = &H80000001
Private Const HKCU = HKEY_CURRENT_USER
Private Const KEY_QUERY_VALUE = &H1&
Private Const ERROR_NO_MORE_ITEMS = 259&
Private Const ERROR_MORE_DATA = 234
Private Const REG_SZ = 1

Private Declare Function RegOpenKeyEx Lib "advapi32" _
    Alias "RegOpenKeyExA" ( _
    ByVal hKey As Long, _
    ByVal lpSubKey As String, _
    ByVal ulOptions As Long, _
    ByVal samDesired As Long, _
    phkResult As Long) As Long

Private Declare Function RegEnumValue Lib "ADVAPI32.DLL" _
    Alias "RegEnumValueA" ( _
    ByVal hKey As Long, _
    ByVal dwIndex As Long, _
    ByVal lpValueName As String, _
    lpcbValueName As Long, _
    ByVal lpReserved As Long, _
    lpType As Long, _
    lpData As Byte, _
    lpcbData As Long) As Long

Private Declare Function RegCloseKey Lib "ADVAPI32.DLL" ( _
    ByVal hKey As Long) As Long

Public Function GetPrinterFullNames() As String()
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GetPrinterFullNames
' By Chip Pearson, chip@cpearson.com, www.cpearson.com
' Returns an array of printer names, where each printer name
' is the device name followed by the port name. The value can
' be used to assign a printer to the ActivePrinter property of
' the Application object. Note that setting the ActivePrinter
' changes the default printer for Excel but does not change
' the Windows default printer.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim Printers() As String ' array of names to be returned
Dim PNdx As Long    ' index into Printers()
Dim hKey As Long    ' registry key handle
Dim Res As Long     ' result of API calls
Dim Ndx As Long     ' index for RegEnumValue
Dim ValueName As String ' name of each value in the printer key
Dim ValueNameLen As Long    ' length of ValueName
Dim DataType As Long        ' registry value data type
Dim ValueValue() As Byte    ' byte array of registry value value
Dim ValueValueS As String   ' ValueValue converted to String
Dim CommaPos As Long        ' position of comma character in ValueValue
Dim ColonPos As Long        ' position of colon character in ValueValue
Dim M As Long               ' string index

' registry key in HCKU listing printers
Const PRINTER_KEY = "Software\Microsoft\Windows NT\CurrentVersion\Devices"

PNdx = 0
Ndx = 0
' assume printer name is less than 256 characters
ValueName = String$(256, Chr(0))
ValueNameLen = 255
' assume the port name is less than 1000 characters
ReDim ValueValue(0 To 999)
' assume there are less than 1000 printers installed
ReDim Printers(1 To 1000)

' open the key whose values enumerate installed printers
Res = RegOpenKeyEx(HKCU, PRINTER_KEY, 0&, _
    KEY_QUERY_VALUE, hKey)
' start enumeration loop of printers
Res = RegEnumValue(hKey, Ndx, ValueName, _
    ValueNameLen, 0&, DataType, ValueValue(0), 1000)
' loop until all values have been enumerated
Do Until Res = ERROR_NO_MORE_ITEMS
    M = InStr(1, ValueName, Chr(0))
    If M > 1 Then
        ' clean up the ValueName
        ValueName = Left(ValueName, M - 1)
    End If
    ' find position of a comma and colon in the port name
    CommaPos = InStr(1, ValueValue, ",")
    ColonPos = InStr(1, ValueValue, ":")
    ' ValueValue byte array to ValueValueS string
    On Error Resume Next
    ValueValueS = Mid(ValueValue, CommaPos + 1, ColonPos - CommaPos)
    On Error GoTo 0
    ' next slot in Printers
    PNdx = PNdx + 1
    Printers(PNdx) = ValueName & " on " & ValueValueS
    ' reset some variables
    ValueName = String(255, Chr(0))
    ValueNameLen = 255
    ReDim ValueValue(0 To 999)
    ValueValueS = vbNullString
    ' tell RegEnumValue to get the next registry value
    Ndx = Ndx + 1
    ' get the next printer
    Res = RegEnumValue(hKey, Ndx, ValueName, ValueNameLen, _
        0&, DataType, ValueValue(0), 1000)
    ' test for error
    If (Res <> 0) And (Res <> ERROR_MORE_DATA) Then
        Exit Do
    End If
Loop

' shrink Printers down to used size
ReDim Preserve Printers(1 To PNdx)
Res = RegCloseKey(hKey)
' Return the result array
GetPrinterFullNames = Printers
End Function

次に、この関数を使用して PDF プリンター名を取得します。

Public Function FindPDFPrinter() As String
'this function finds the exact printer name for the Adobe PDF printer

        Dim Printers() As String
        Dim N As Integer
        FindPDFPrinter = ""
        Printers = GetPrinterFullNames()
        For N = LBound(Printers) To UBound(Printers)
            If InStr(1, Printers(N), "PDF") Then
              FindPDFPrinter = Printers(N)
            End If
        Next N

End Function

次に、Application.ActivePrinter をその文字列に設定します。

本当にポートが必要な場合は、ストリングの端から引き抜くことができます。

于 2013-01-10T23:50:53.943 に答える