How do I search for the default printer and print plain text on a dot matrix printer in .Net?

12

We have a thermal printer that does not support graphics printing - in this case, I'll have to send simple texts for it.

Considering that our application will run on several different computers, each of them connected to a different printer and that in turn may be configured on different ports on each machine (% with%,% with%, etc), we will have to adopt the default printer as the output destination of the text to be printed.

So In .NET, how can I search for the default printer and print raw text on it?

    
asked by anonymous 17.12.2013 / 15:02

2 answers

10

To pick up the default printer use the PrinterSettings (in English) . Example:

var configImpressora = new PrinterSettings();
Console.WriteLine(configImpressora.PrinterName);

Note that this way you are using the Windows manager to get this information. And what you need to do to send the data is just the opposite.

Getting the standard printer will not help much because it does not guarantee that the printer that is there is suitable for what you want. And even if you send it to it, it will send to the Windows manager which is just what you DO NOT want to do.

Unless I do not know anything about it, I doubt that part will help you in anything.

As for the second part of the question:

Essentially you need to write directly to the port, usually PRN or LPT1 or COM1 . sending directly to the port you avoid going through the Windows print manager,

Simplified example (does not have the quality that a production code should have):

var impressora = new System.IO.StreamWriter(@"\.\PRN");
impressora.Write((char)15); //inicia negrito na maioria das impressoras matriciais
impressora.Write("Teste");
impressora.Flush();
impressora.Close();

When I needed to send it to a standard printer, that's basically what I did.

If you need to choose where the printer is on each machine, I'm afraid you should have a local configuration indicating where the printer is. It can be a simple text file, but it can be a local database, the Windows registry or simply allow the user to choose when to print, which can be enough in many cases.

I placed it in Github for future reference .

    
17.12.2013 / 16:24
4

After a few searches, the way we can do it is not as elegant (we had to call P / Invoke 1 ), but it worked very well.

using System.Drawing.Printing;
(...)
public void ImprimeConteudoDiretamenteNaImpressoraPadrao(string conteudo)
{
    string nomeImpressoraPadrao = (new PrinterSettings()).PrinterName;
    RawPrinterHelper.SendStringToPrinter(nomeImpressoraPadrao, conteudo);
}
  • Method RawPrinterHelper.SendStringToPrinter is defined in the removed code this article ( Step 8 ) .
  • 17.12.2013 / 21:14