Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0 printing Printer
I have a application that currently a user has to run and once the app is running it sends a reset command to the printer. Here is my current code:
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Windows;
using System.Security.Permissions;
using System.Threading;
using System.ServiceProcess;
using System.Printing;
 

//working but not showing form
namespace test_app
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            //this.ShowInTaskbar = false;
            this.Load += new EventHandler(Form1_Load);
            
        }
 
        public class RawPrinterHelper
        {
            // Structure and API declarions:
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
            public class DOCINFOA
            {
                [MarshalAs(UnmanagedType.LPStr)]
                public string pDocName;
                [MarshalAs(UnmanagedType.LPStr)]
                public string pOutputFile;
                [MarshalAs(UnmanagedType.LPStr)]
                public string pDataType;
            }
            [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
            public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
 
            [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
            public static extern bool ClosePrinter(IntPtr hPrinter);
 
            [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
            public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
 
            [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
            public static extern bool EndDocPrinter(IntPtr hPrinter);
 
            [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
            public static extern bool StartPagePrinter(IntPtr hPrinter);
 
            [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
            public static extern bool EndPagePrinter(IntPtr hPrinter);
 
            [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
            public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
 
            // SendBytesToPrinter()
            // When the function is given a printer name and an unmanaged array
            // of bytes, the function sends those bytes to the print queue.
            // Returns true on success, false on failure.
            public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
            {
                Int32 dwError = 0, dwWritten = 0;
                IntPtr hPrinter = new IntPtr(0);
                DOCINFOA di = new DOCINFOA();
                bool bSuccess = false; // Assume failure unless you specifically succeed.

                di.pDocName = "My C#.NET RAW Document";
                di.pDataType = "RAW";
 
                // Open the printer.
                if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
                {
                    // Start a document.
                    if (StartDocPrinter(hPrinter, 1, di))
                    {
                        // Start a page.
                        if (StartPagePrinter(hPrinter))
                        {
                            // Write your bytes.
                            bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
                            EndPagePrinter(hPrinter);
                        }
                        EndDocPrinter(hPrinter);
                    }
                    ClosePrinter(hPrinter);
                }
                // If you did not succeed, GetLastError may give more information
                // about why not.
                if (bSuccess == false)
                {
                    dwError = Marshal.GetLastWin32Error();
                }
                return bSuccess;
            }
 

            public static bool SendStringToPrinter(string szPrinterName, string szString)
            {
                IntPtr pBytes;
                Int32 dwCount;
                //How many characters are in the string?
                dwCount = szString.Length;
                //Assume that the printer is expecting ANSI text, and then convert the string to ANSI text.
                pBytes = Marshal.StringToCoTaskMemAnsi(szString);
                //Send the converted ANSI string to the printer.
                SendBytesToPrinter(szPrinterName, pBytes, dwCount);
                Marshal.FreeCoTaskMem(pBytes);
                return true;
            }
 
        }
 

        private void Form1_Load(object sender, System.EventArgs e)//This part works!!
        {
 

            timer1.Enabled = true;
            timer1.Interval = 1000;
            timer1.Start();
 

            backgroundWorker1.RunWorkerAsync();   
 
    
        }
 

 
        private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Visible = !label1.Visible;
            
        }
 
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
 
            progressBar1.Value = 200;
 
            ServiceController spoolservice = new ServiceController();
            spoolservice.ServiceName = "Spooler";
            string svcStatus = spoolservice.Status.ToString();
 

            switch (svcStatus.ToString())
            {
                case "Running":
 
                    spoolservice.Stop();
                    Thread.Sleep(3000);
                    spoolservice.Start();
                    break;
 
                case "Stopped":
                    spoolservice.Start();
                    Thread.Sleep(3000);
                    break;
            }
 

            progressBar1.Value = 400;
 
            Thread.Sleep(3000);
            progressBar1.Value = 600;
            foreach (string path in Directory.GetFiles("C:\\Windows\\System32\\spool\\PRINTERS"))
                File.Delete(path);
            progressBar1.Value = 800;
            string szString = "~JR";
            PrintDialog printDialog = new PrintDialog();
            printDialog.PrinterSettings = new PrinterSettings();
            printDialog.PrinterSettings.PrinterName = "Label Printer";
            Form1.RawPrinterHelper.SendStringToPrinter(printDialog.PrinterSettings.PrinterName, szString);
            progressBar1.Value = 1000;
 
            Thread.Sleep(20000);
 
            this.Close();
 
          
        }
               
    }
    
 
}
 
 
I would like to use the PrintSystemJobInfo.JobStatus Property within a switch statement to allow the app to look for specific printing problems, i'm just not sure how to use it with what I currently have. Please Help!
Posted 11-Dec-12 11:47am
Comments
Sergey Alexandrovich Kryukov at 11-Dec-12 19:09pm
   
Why doing all that? Why not using System.Drawing.Printing, which does not require P/Invoke at all?
 
Using timer, Thread.Sleep, hard-coded immediate constants, especially path names here — everything is very bad, not acceptable.
--SA
Dustin Prevatt at 12-Dec-12 9:09am
   
Sorry I'm new to this and was just looking for help. What can I do to make it better>?
Dustin Prevatt at 12-Dec-12 9:13am
   
I found everything above form_load by googling how to send a string to a printer, so if that is not needed please let me know.
Akbar Ali Hussain at 12-Dec-12 14:54pm
   
Please explain why you want to send reset command to the printer. What type of printer it is?
Dustin Prevatt at 12-Dec-12 15:11pm
   
This is a Zebra label printer, and for some reason everytime the printer runs out of paper the printer then has to be reset in order for it to work properly again.
Akbar Ali Hussain at 12-Dec-12 16:09pm
   
Read the printer catalog. There should be some DOS commands (or combination of ASCII characters) to reset the printer. If yes, create a BAT file with the command and execute using Shell command.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 410
1 Maciej Los 280
2 OriginalGriff 248
3 CHill60 186
4 Sinisa Hajnal 145


Advertise | Privacy | Mobile
Web04 | 2.8.141022.2 | Last Updated 11 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100