How to fetch the default printer and print plain text on a matrix printer no.NET?

We have a thermal printer that does not support printing graphic elements - in this case I will have to send simple texts to it.

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

So: in .NET, how can I fetch the default printer and print "raw" texts on it?

Author: Maniero, 2013-12-17

2 answers

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

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

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

Picking up which is the default printer won't help much because it doesn't guarantee that the printer that is there is suitable for what you want. And even if you send to it, it will send to the Windows that is precisely what you do not want to do.

Unless I know something about it, I doubt that this part will help you in anything.

As for the second part of the question:

Essentially you need to write directly on the port, typically PRN or LPT1 or COM1. by 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 ter):

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 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 setting 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 at the time of having it printed, which can be enough in many case.

I put on GitHub for future reference.

 10
Author: Maniero, 2020-09-01 13:57:24

After a few searches, it follows the way we managed to do: it's not so elegant (we had to appeal to P/Invoke calls1), but it worked very well.

using System.Drawing.Printing;
(...)
public void ImprimeConteudoDiretamenteNaImpressoraPadrao(string conteudo)
{
    string nomeImpressoraPadrao = (new PrinterSettings()).PrinterName;
    RawPrinterHelper.SendStringToPrinter(nomeImpressoraPadrao, conteudo);
}
  1. method RawPrinterHelper.SendStringToPrinter is defined in the code taken from this article (Step 8).
 4
Author: Jônatas Hudler, 2013-12-24 17:28:28