[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Restart the print spooler in C#

[Restart the print spooler in C#]

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.