c# setting a printer

后端 未结 1 1166
旧时难觅i
旧时难觅i 2021-01-14 06:29

Hello and thank you for you time on this question, I\'m trying change a Active Printer according to the choice that user chooses in excel. However I\'m having some trouble.

1条回答
  •  终归单人心
    2021-01-14 07:15

    The correct answer is (i.e.):

    xlApp.ActivePrinter = "\\\\RR-PS1\\CORPPRT58-Copier Room on Ne00:";
    

    An important part is the 'Ne00:' This is the port on which this printer can be found. This is different on each computer and can be found in registry at HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices.

    Another problem is the concatenation string 'on'. This may be valid when working with an English excel but it's translated to other languages!

    I had the same problem but there aren't many complete examples I could find so here is mine:

    // Open excel document
    var path = @"c:\path\to\my\doc.xlsx";
    
    Microsoft.Office.Interop.Excel.Application _xlApp;
    Microsoft.Office.Interop.Excel.Workbook _xlBook;
    _xlApp = new Microsoft.Office.Interop.Excel.Application();
    _xlBook = _xlApp.Workbooks.Open(path);
    _xlBook.Activate();
    
    var printer = @"EPSON LQ-690 ESC/P2";
    var port = String.Empty;
    
    // Find correct printerport
    using (RegistryKey key = Registry.CurrentUser.OpenSubKey(path))
    {
        if (key != null)
        {
            object value = key.GetValue(printer);
            if (value != null)
            {
                string[] values = value.ToString().Split(',');
                if (values.Length >= 2) port = values[1];
            }
        }
    }
    
    // Set ActivePrinter if not already set
    if (!_xlApp.ActivePrinter.StartsWith(printer))
    {
        // Get current concatenation string ('on' in enlgish, 'op' in dutch, etc..)
        var split = _xlApp.ActivePrinter.Split(' ');
        if (split.Length >= 3)
        {
            _xlApp.ActivePrinter = String.Format("{0} {1} {2}",
                printer, 
                split[split.Length - 2], 
                port);
        }
    }
    
    // Print document
    _xlBook.PrintOutEx();
    

    It's far for perfect since I'm not aware of any other translations. If 'on' is translated with spaces, above will fail. But i'm guessing that the solution will work for most clients. You can easily get the current concatenation string by looking at the currect value of ActivePrinter.

    A more failproof method would be to strip the printer name and the assigned port and what remains is the concatenation string. But then you would have to loop through all installed printers and check for a match.

    Another test I personally do it check if the printer is installed on the system:

    if(PrinterSettings.InstalledPrinters.Cast().ToList().Contains(printer)) {
        //Set active printer...
    }
    

    0 讨论(0)
提交回复
热议问题