C#
- 2 ответа
- 0 вопросов
0
Вклад в тег
internal static string SelectPrinter()
{
System.Windows.Forms.PrintDialog prntDlg = new System.Windows.Forms.PrintDialog();
if (prntDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (prntDlg.PrinterSettings.IsValid)
return prntDlg.PrinterSettings.PrinterName;
}
return "";
}
internal static string GetPort(string printerName)
{
var devices = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Devices"); //Read-accessible even when using a locked-down account
try
{
foreach (string name in devices.GetValueNames())
{
if (name == printerName)
{
var value = (String)devices.GetValue(name);
var port = Regex.Match(value, @"(,\w+:)", RegexOptions.IgnoreCase).Value;
port = port.Replace(",", "");
return port;
}
}
}
catch
{
throw;
}
return "";
}
internal static string GetActivePrinter()
{
string printer = SelectPrinter();
if (printer != "")
{
string port = GetPort(printer);
if (port != "")
return printer + " (" + port + ")";
else
return "";
}
else
return "";
}
internal static void PrintExcelSheet(Excel.Application app, Excel.Worksheet sheet, String activePrinter)
{
try
{
app.ActivePrinter = activePrinter;
sheet.PrintOutEx();
}
catch (Exception e)
{
Console.WriteLine("Print error:\r\n" + e.Message);
}
}
string printerName = GetActivePrinter();
if (printerName != "")
{
Console.WriteLine("Menu send to printer: " + printerName);
PrintExcelSheet(xlApp, xlWorkSheet, printerName);
}