2017-04-26 86 views
0

你好stackoverflow社区,我正在开发一个简单的Windows窗体应用程序,它有一个侦听器在特定目录侦听一个txt文件,如果侦听器检测到一个新文件,它会自动将txt文件发送到本地默认打印机,但它也会显示“保存打印输出为”对话框,我需要打印过程是即时的,无需与任何对话框交互。如何删除“保存打印输出为”对话框时打印一个txt文件#

为此,我使用当前命名空间“using System.Drawing.Printing; using System.IO;”我已经看到了Print()方法的定义,但好像代码被保护了,所以我不能访问“保存打印输出为”对话框。有任何想法吗?

这里是我的代码...

的fileWatcher:

private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e) 
{ 
    try 
    { 
     MyPrintMethod(e.FullPath); 
    } 
    catch (IOException) 
    { 
    } 
} 

我的打印方法:

private void MyPrintMethod(string path) 
{ 
    string s = File.ReadAllText(path); 
    printDocument1.PrintController = new StandardPrintController(); 
    printDocument1.PrintPage += delegate (object sender1, PrintPageEventArgs e1) 
    { 
     e1.Graphics.DrawString(s, new Font("Times New Roman", 12), new SolidBrush(Color.Black), new RectangleF(0, 0, printDocument1.DefaultPageSettings.PrintableArea.Width, printDocument1.DefaultPageSettings.PrintableArea.Height)); 

    }; 
    try 
    { 
     printDocument1.Print(); 
    } 
    catch (Exception ex) 
    { 
     throw new Exception("Exception Occured While Printing", ex); 
    } 
} 
+0

我不能看到你指定打印到的实际打印机。 –

+0

尝试此链接的想法或做一个谷歌搜索 - http://stackoverflow.com/questions/10572420/how-to-skip-the-dialog-of-printing-in-printdocument-print-and-print-page- direc – MethodMan

+0

'printDocument1'在哪里定义?我只是复制并粘贴了你的代码,但我不得不添加'var printDocument1 = new PrintDocument();'来编译它,并且在没有对话框的情况下,它在我的默认打印机上正常打印。 –

回答

1

那个时候正在使用的打印机出现的对话框是文档编辑器,像Microsoft XPS Document WriterMicrosoft Print to PDF。由于您没有按名称指定打印机,问题很可能是这是当前的默认打印机。

如果你知道你要使用的打印机的名称,那么你可以像这样指定它:

printDocument1.PrinterSettings.PrinterName = 
    @"\\printSrv.domain.corp.company.com\bldg1-floor2-clr"; 

如果你不知道这个名字,那么可能是你能做的最好是问用户哪一个他们想要打印到。你可以像这样安装的打印机列表:

var installedPrinters = PrinterSettings.InstalledPrinters; 

然后选择一个时,你可以指定名称的第一个代码样本。这里有一些代码,你可以用来提示用户打印机,并将打印机设置为他们选择的打印机:

Console.WriteLine("Please select one of the following printers:"); 
for (int i = 0; i < installedPrinters.Count; i++) 
{ 
    Console.WriteLine($" - {i + 1}: {installedPrinters[i]}"); 
} 

int printerIndex; 
do 
{ 
    Console.Write("Enter printer number (1 - {0}): ", installedPrinters.Count); 
} while (!int.TryParse(Console.ReadLine(), out printerIndex) 
     || printerIndex < 1 
     || printerIndex > installedPrinters.Count); 

printDocument1.PrinterSettings.PrinterName = installedPrinters[printerIndex - 1]; 
+0

谢谢,我会尝试你的解决方案,如果它的工作,我会选择你的答案作为最好的答案;) –

+0

它的工作!非常感谢! –

+0

所以如果我明白这一点,你需要指定打印机? –