In the course of project development, it is sometimes necessary to invoke a Third-party program to implement some of the functions of the system, such as the swftools plug-ins that need to be used in this article, how to use the plug-in in the program, and how does the plug-in translate PDF files into SWF files? Then we'll do a simple introduction.
In the. NET platform, C # provides an operation for local and remote access to the process that enables the system to start and stop. This class is System.Diagnostics.Process, so let's take a look at the class first.
I. Parsing the System.Diagnostics.Process class
Using process classes in C # can provide access to local and remote processes that enable and stop system processes, and that class can manage system processes. Some common methods in this class are: Start (), Kill (), WaitForExit (), Startinfo,filename,createnowindow, and so on.
1.Start () Method: Start (or reuse) the process resource specified by the StartInfo property of this process component and associate it with the component. True if the process resource is started, or false if the new process resource is not started (for example, if an existing process is reused).
The implementation code for this method is described in detail:
///<devdoc>///<para>///<see cref= ' SYSTEM.DIAGNOSTICS.P
Rocess '/> If the process resource is reused rather than started, the reused process is associated with this <see cref = ' System.Diagnostics.Process '/> Parts. </para>///</devdoc> [Resourceexposure (Resourcescope.none)] [Resourceconsumption (RESOURC
Escope.machine, Resourcescope.machine)] public bool Start () {close ();
ProcessStartInfo startinfo = startinfo; if (StartInfo.FileName.Length = = 0) throw new InvalidOperationException (SR. GetString (SR.
filenamemissing)); if (startinfo.useshellexecute) {#if!
Feature_pal return Startwithshellexecuteex (startinfo); #else throw new InvalidOperationException (SR.
GetString (Sr.net_perm_invalid_val, "Startinfo.useshellexecute", true)); #endif//!
Feature_pal} else {return startwithcreateprocess (startinfo); }
}
2.Kill () Method: Immediately stop the associated process. Kill forces the process to terminate, and the Kill method executes asynchronously. After you call the Kill method, call the WaitForExit method to wait for the process to exit, or check the HasExited property to determine if the process has exited.
The implementation code for this method is described in detail:
[Resourceexposure (Resourcescope.machine)]
[Resourceconsumption (Resourcescope.machine)]
public void Kill () {
safeprocesshandle handle = null;
try {
handle = Getprocesshandle (nativemethods.process_terminate);
if (! Nativemethods.terminateprocess (handle,-1))
throw new Win32Exception ();
}
finally {
releaseprocesshandle (handle);
}
}
Safeprocesshandle getprocesshandle (int access) {return Getprocesshandle (access, true);
///<devdoc>///Gets the short term handle of the process with the given access rights.
If the handle is stored in the current process object, it is used.
Note that the handle we store in the current process object will have all the access rights we need. </devdoc>///<internalonly/> [Resourceexposure (Resourcescope.none)] [Resourceconsumption (Re
Sourcescope.machine, Resourcescope.machine)] safeprocesshandle getprocesshandle (int access, bool throwifexited) { Debug.WriteLineIf (Processtracing.traceverbose, "getprocesshandle" (Access = 0x) + Access.
ToString ("X8", CultureInfo.InvariantCulture) + ", throwifexited =" + throwifexited + ")"); #if DEBUG if (processtracing.traceverbose) {stackframe calledfrom = new StackTrace (true).
GetFrame (0);
Debug.WriteLine ("called from" + calledfrom.getfilename () + ", line" + calledfrom.getfilelinenumber ()); #endif if (haveprocesshandle) {if (throwifexited) {//Because Hasprocesshandle is a TRUE, we know we have the process handle//open at least synchronize access, so we can wait for it//zero timeout to see if the process has exited.
Processwaithandle waitHandle = null;
try {waitHandle = new Processwaithandle (m_processhandle); if (WaitHandle.WaitOne (0, false)) {if (haveprocessid) throw new InvalidOperationException ( SR. GetString (SR.
processhasexited, Processid.tostring (CultureInfo.CurrentCulture)); else throw new InvalidOperationException (SR. GetString (SR.
processhasexitednoid));
finally {if (WaitHandle!= null) {waithandle.close ());
}} return m_processhandle; else {ensurestate (State.haveid |
state.islocal);
Safeprocesshandle handle = Safeprocesshandle.invalidhandle; #if!
Feature_pal handle = processmanager.openprocess (ProcessID, Access, throwifexited);
#elseIntPtr Pseudohandle = nativemethods.getcurrentprocess (); Get a real handle if (! Nativemethods.duplicatehandle New HandleRef (this, pseudohandle), new HandleRef (This, Pseudohan
DLE), New HandleRef (this, pseudohandle), out handle,
0, false, Nativemethods.duplicate_same_access |
Nativemethods.duplicate_close_source)) {throw new win32exception (); #endif//!
Feature_pal if (throwifexited && (Access & Nativemethods.process_query_information)!= 0) {
if (nativemethods.getexitcodeprocess (handle, out ExitCode) && ExitCode!= nativemethods.still_active) { throw new InvalidOperationException (SR. GetString (SR.
processhasexited, Processid.tostring (CultureInfo.CurrentCulture));
} return handle; }
}
3.WaitForExit () Method: Indicates that the <see cref = ' System.Diagnostics.Process '/> Component waits for the specified number of milliseconds to exit the associated process.
The implementation code for this method is described in detail:
public bool WaitForExit (int milliseconds) {Safeprocesshandle handle = null;
BOOL exited;
Processwaithandle processwaithandle = null;
try {handle = Getprocesshandle (Nativemethods.synchronize, false); if (handle.
Isinvalid) {exited = true;
else {processwaithandle = new processwaithandle (handle);
if (Processwaithandle.waitone (milliseconds, false)) {exited = true;
signaled = true;
else {exited = false;
signaled = false;
finally {if (Processwaithandle!= null) {Processwaithandle.close ()}}}; }//If We have a hard timeout, we cannot wait for the streams If (output!= null && millise Conds = = 1) {output.
Waitutileof (); } if (Error!= null && milliseconds = = 1) {error.
Waitutileof (); } releaseprocesshandle (handle);
} if (exited && watchforexit) {raiseonexited ();
return exited;
}
Internal Processwaithandle (Safeprocesshandle processhandle): Base () {
safewaithandle waitHandle = null;
BOOL succeeded = Nativemethods.duplicatehandle (
new HandleRef (This, nativemethods.getcurrentprocess ()),
ProcessHandle,
new HandleRef (This, nativemethods.getcurrentprocess ()), out
WaitHandle,
0,
false,
nativemethods.duplicate_same_access);
if (!succeeded) {
marshal.throwexceptionforhr (Marshal.gethrforlastwin32error ());
}
This. Safewaithandle = WaitHandle;
}
4.StartInfo property: Gets or sets the property to pass to the Start method of the Process. StartInfo represents a set of parameters used to start a process. When calling start, StartInfo is used to specify the process to start. The only startinfo member that must be set is the FileName property.
The implementation code for this method is described in detail:
[Browsable (False), designerserializationvisibility (designerserializationvisibility.content), Monitoringdescription (SR. ProcessStartInfo)] public
ProcessStartInfo startinfo {get
{
if (startinfo = = null) {
startinfo = new Pro Cessstartinfo (this);
}
return startinfo;
}
[Resourceexposure (Resourcescope.machine)]
set {
if (value = = null) {
throw new ArgumentNullException ("value");
}
StartInfo = value;
}
}
5.CreateNoWindow property: Gets or sets a value indicating whether to start the process in a new window.
The implementation code for this method is described in detail:
[
DefaultValue (false),
monitoringdescription (SR. Processcreatenowindow),
Notifyparentproperty (True)
] public
bool CreateNoWindow {get
{return CreateNoWindow;
set {CreateNoWindow = value;}
}
The above is a brief description of the three common methods and two common properties of the class, it is not necessary to have a comprehensive understanding of the underlying implementation of each property method and property in the actual development project, but it is recommended that when learning this class, it is helpful for us to have a proper understanding of some of the class's method implementations to facilitate our mastery of the class.
Two. How to implement PDF file into SWF file
If you need to convert a PDF file to a SWF file in your project, you can introduce the Swftools plug-in into your project, the main feature of the plug-in: PDF to SWF converter. Builds one frame per page. Enables you to have fully formatted text in the Flash movie, including tables, formulas, graphics, and so on. It is based on Derek B. Noonburg's xpdf PDF parser.
A brief introduction to the plug-in's common parameters:
-H, –help print short helps message and exit printing help information
-V, –version print version info and exit prints the build number
-O, –output file.swf Direct output to file.swf. If file.swf contains ' 13568621′ (file13568630.swf), then each page specifies the output SWF filename
-p, –password password use password for deciphering the PDF. Specify the password to open the PDF
-Z, –zlib use Flash 6 (MX) zlib compression. zlib compression mechanism using Flash 6
-I, –ignore allows pdf2swf to change the draw order of the PDF. This generated allows the program to modify the order in which the PDF is drawn, which may result in a difference from the original
The above is a few commonly used parameters, specific wipe parameter list see: http://www.swftools.org/.
A simple introduction to the classes and plug-ins that implement this operation, and then provides an operational method to implement the function:
<summary>///PDF format to swf///</summary>///<param name= "Pdfpathparameter" > Original video file address, such as/a /b/c.pdf</param>///<param name= "Swfpathparameter" > after-generated FLV file address, such as/a/b/c.swf</param>/// M name= "Beginpage" > Conversion start Page </param>///<param name= "endpage" > Transition End page </param>///<param name= " Photoquality "> Photo quality </param>///<returns></returns> public static bool Pdfconversionswf (string Pdfpathparameter, string swfpathparameter, int beginpage, int endpage, int photoquality) {if (string.
IsNullOrEmpty (Pdfpathparameter)) {throw new ArgumentNullException (Pdfpathparameter); } if (string.
IsNullOrEmpty (Swfpathparameter)) {throw new ArgumentNullException (Swfpathparameter);
} if (EndPage < beginpage) {throw new ArgumentException ("Start pages larger than end pages"); } if (photoquality <= 0) {throw new ArgumenTexception ("Photo quality error");
The var exe = HttpContext.Current.Server.MapPath ("~/tools/swftools-2013-04-09-1007.exe");
var Pdfpath = HttpContext.Current.Server.MapPath (Pdfpathparameter);
var Swfpath = HttpContext.Current.Server.MapPath (Swfpathparameter);
Process p = null; try {if (! File.exists (EXE) | | !
File.exists (Pdfpath)) {return false;
} if (File.exists (Swfpath)) {file.delete (Swfpath);
var sb = new StringBuilder (); Sb.
Append ("\" "+ Pdfpath +" ""); Sb.
Append ("O \" "+ Swfpath +" ""); Sb.
Append ("-S flashversion=9"); Sb.
Append ("-S disablelinks");
if (EndPage > Getpagecount (pdfpath)) {endpage = Getpagecount (Pdfpath); } sb.
Append ("P" + "\" "+ Beginpage +" "+"-"+ EndPage +" ""); The quality of the picture in SWF sb.
Append ("-j" + photoquality); var command = sb.
ToString (); PRocess provides access to local and remote processes that enable the system to start and stop processes.
p = new Process {startinfo = {FileName = exe, Arguments = command,
WorkingDirectory = HttpContext.Current.Server.MapPath ("~/bin/"), UseShellExecute = False,
Redirectstandarderror = True, CreateNoWindow = false};
Start thread P.start ();
Start asynchronous read P.beginerrorreadline ();
Waiting to complete p.waitforexit ();
Start synchronous read//p.standarderror.readtoend (); if (!
File.exists (Swfpath)) return false;
return true; The catch (IOException Ioex) {throw new IOException (Ioex.
message); The catch (Exception ex) {throw new Exception (ex).
message);
finally {if (P!= null) {//Shutdown process p.close ();
Releasing resources p.dispose ();
}
}
}
Three. Summary
In this article, we introduced the C # How to manipulate the class System.Diagnostics.Process of external programs and threads, and introduces the underlying implementation code for some of the common methods of the class, if you need to have a detailed understanding of the class, you can follow the MSDN and. NET underlying source of the relevant comments and articles for careful study. In the introduction of the implementation of the operation of the class at the same time, also made a description of the Swftools plug-in, and enumerated the relevant parameters, if there are high requirements in the project, can be based on the official provision of the API documentation for refactoring.
In project development, any function is unable to do all the functions, in the encoding function, only as far as possible to take into account the generality of the method, the understanding of a certain class and the basic principles of a plug-in and the use of methods, can be based on the corresponding API to add new features.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.