Restart the print spooler in C#

[example]

Every now and then my computer gets confused and thinks the printer is offline. That wouldn’t be so bad except Windows doesn’t provide a simple way to bring the printer back online. Basically you need to shutdown and restart the print spooler. I wrote this example to make that easier.

When you click the Restart button, the program executes the following code.

// Add a reference to System.ServiceProcess.
using System.ServiceProcess;
...
private void btnRestart_Click(object sender, EventArgs e)
{
    Cursor = Cursors.WaitCursor;

    // Stop the spooler.
    ServiceController service = new ServiceController("Spooler");
    if ((!service.Status.Equals(ServiceControllerStatus.Stopped)) &&
        (!service.Status.Equals(ServiceControllerStatus.StopPending)))
    {
        lblStatus.Text = "Stopping spooler...";
        lblStatus.Refresh();

        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped);
    }

    // Start the spooler.
    lblStatus.Text = "Restarting spooler...";
    lblStatus.Refresh();
    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running);

    lblStatus.Text = "Done";
    Cursor = Cursors.Default;
}

The program uses the System.ServiceProcess.ServiceController class so the code makes that easier by starting with a using System.ServiceProcess directive. To use that namespace, add System.ServiceProcess to the project’s references.

When you click the button, the code creates a new ServiceController for the service named “Spooler.” If the spooler isn’t currently stopped or pending a stop, the code calls its Stop method and then waits until the spooler stops.

Now that the spooler is stopped, the code calls its Start method and waits until it is finished starting.

This is pretty easy but there is a catch. You need to run the program with sufficient privileges to stop and restart the spooler. One way to do that is to right-click on the program’s executable and select “Run as administrator.”


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in printing, system and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *