Running and Closing applications using C#
August 27, 2008 in C# by Michael Chrisman 0 Comments
Sometimes you need to run an external command. This is usually when there is no API for the application. An example is to use Adobe Acrobat reader to print a PDF file.
The class we will use to open the application is the Process class. It is in the System.Diagnostics namespace. So the first step is to include the namespace.
1: using System.Diagnostics;
Now we have to create our application variable.
1: Process AcroReader = new Process();
Of course we have only created an empty application container. It needs to know a couple of things before we can start it. The file name to run and any startup parameters come to mind.
1: AcroReader.StartInfo.FileName = "C:\program files\Adobe\Reader\bin\acrord32.exe";2: AcroReader.StartInfo.Arguments = "/t myfile.pdf \\servername\printername";
For the filename, be sure to include the full path if the command is not on the command path. FYI, the arguments I have listed will print the file named 'myfile.pdf' to a printer share.
Now all we have to do is run the command. This is done by invoking the start() method.
1: ArcoReader.Start();
Of course, once the command is done, it might be useful to close the application window. To do this, we use the CloseMainWindow() method.
1: ArcoReader.CloseMainWindow();
So let's put is all together.
1: using System;2: using System.Diagnostics;3:4: namespace demo5: {6: class ProcessDemo7: {8: static void Main(string[] args)9: {10: Process AcroReader = new Process();11:12: AcroReader.StartInfo.FileName = "C:\program files\Adobe\Reader\bin\acrord32.exe";13: AcroReader.StartInfo.Arguments = "/t myfile.pdf \\servername\printername";14:15: AcroReader.Start();16:17: // wait for app to finish18:19: AcroReader.CloseMainWindow();20: }21: }22: }