How to find the default printer and print plain text on a dot matrix printer on . NET?

Asked

Viewed 6,298 times

12

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

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

Therefore: No. NET, how can I find the default printer and print "raw" text on it?

2 answers

10


To get 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 the Windows manager to get this information. And what you need to do to send the data is just the opposite.

Picking which is the default 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 her, it will send it to the Windows manager which is just what you DON’T want to do.

Unless I don’t know something about it, I doubt that part will help you at all.

The second part of the question:

Essentially you need to write directly on the door, normally 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 code in production 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 had 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’ll have to have a local setting indicating where the printer is. It may be a simple text file, but it may be a local database, the Windows registry or simply allow the user to choose at the time of having it printed, which may be sufficient in many cases.

I put in the Github for future reference.

4

After a few searches, it follows the way we were able to do it: It’s not so elegant (we had to appeal to P/Invoke calls1), but it worked really 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 removed of this article (Step 8).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.