Code instance analysis of process suspend and recovery in C #

Source: Internet
Author: User
This article mainly introduces the process of C # in the Suspend and resume operation method, very good, with reference value, the need for friends can refer to the following

1. Origin:

is still a requirement caused by modular programming. The product manager is difficult to wait, the female product manager is even more ~:p

Purely joking, technical solutions and product managers have nothing to do, Taro mo Strange!

VCU10 project reconfiguration, requires each function module to be implemented in an independent process, such as: Audio and video conversion module, if the independent process to achieve, how to control its pause, continue and other functions?

Thread can suspend, resume,c# built-in process no such method, how to complete?

There is no way, Vista. Feeling to thick when the clear turn thin, this feeling can be a remembrance!

The previous chapter describes the inter-process data transfer method, which is also a sample demonstration of the control and data interaction methods.

2. Undisclosed API functions: Ntsuspendprocess, Ntresumeprocess

This type of function is not found on MSDN.

Reason, because they are between Windows API and kernel API, the power is not to be underestimated. Be afraid of 28 rake programmer abuse and cause trouble, so secret hidden.

In fact, there is a ntterminateprocess, because the process has a Kill method, so it can not be used.

But the hidden things, as long as there is value, will be turned out, good wine is not afraid of the alley deep!

Well, based on it, design a process management class to implement the process of modular programming to control this requirement.

3, Processmgr

Go straight to the code, encapsulate a process snap-in:

public static class Processmgr {//<summary>//The Process-specific access rights. </summary> [Flags] public enum Processaccess:uint {//<summary>/Required to terminate a pro   Cess using TerminateProcess.   </summary> Terminate = 0x1,///<summary>//Required to create a thread.   </summary> CreateThread = 0x2,///<summary>//undocumented. </summary> Setsessionid = 0x4,///<summary>/Required to perform a operation on the address spa   Ce of a process (see Virtualprotectex and WriteProcessMemory). </summary> vmoperation = 0x8,///<summary>/Required to read memory in a process using READPROCE   Ssmemory. </summary> Vmread = 0x10,///<summary>/Required to write to memory in a process using Writeproc   Essmemory. </summary> vmwrite = 0x20,///<summary>/Required to duplicate a handle using DupliCatehandle.   </summary> Duphandle = 0x40,///<summary>//Required to create a process. </summary> CreateProcess = 0x80,///<summary>/Required to set memory limits using Setprocesswor   Kingsetsize. </summary> Setquota = 0x100,///<summary>/Required to set certain information about a process,   such as its priority class (see Setpriorityclass). </summary> setinformation = 0x200,///<summary>/Required to retrieve certain information about A process, such as its tokens, exit code, and priority class (see OpenProcessToken, GetExitCodeProcess, Getpriorityclass   , and Isprocessinjob).   </summary> queryinformation = 0x400,///<summary>//undocumented.   </summary> Setport = 0x800,///<summary>//Required to suspend or resume a process. </summary> Suspendresume = 0x800,///<summary>/Required to retrieve CertaIn information about a process (see QUERYFULLPROCESSIMAGENAME).   A handle that have the Process_query_information access right is automatically granted process_query_limited_information.  </summary> querylimitedinformation = 0x1000,///<summary>//Required to wait for the process to   Terminate using the wait functions. </summary> Synchronize = 0x100000} [DllImport ("Ntdll.dll")] private static extern uint Ntresumeprocess ([in  ] IntPtr ProcessHandle);  [DllImport ("Ntdll.dll")] private static extern uint Ntsuspendprocess ([in] IntPtr processhandle);    [DllImport ("kernel32.dll", SetLastError = True)] private static extern IntPtr OpenProcess (processaccess desiredaccess,  BOOL Inherithandle, int processId);  [DllImport ("kernel32.dll", SetLastError = True)]  [Return:marshalas (Unmanagedtype.bool)] private static extern Bool CloseHandle ([in] IntPtr handle);   public static void suspendprocess (int processId) {IntPtr hproc = IntPtr.Zero; Try  {//Gets the handle to the Process Hproc = OpenProcess (Processaccess.suspendresume, False, processId);   if (hproc! = IntPtr.Zero) ntsuspendprocess (hproc);    } finally {//Don ' t forget to close handle you created.   if (hproc! = IntPtr.Zero) CloseHandle (hproc);   }} public static void resumeprocess (int processId) {IntPtr hproc = IntPtr.Zero;    try {//Gets the handle to the Process Hproc = OpenProcess (Processaccess.suspendresume, False, processId);   if (hproc! = IntPtr.Zero) ntresumeprocess (hproc);    } finally {//Don ' t forget to close handle you created.   if (hproc! = IntPtr.Zero) CloseHandle (hproc); }  } }

4. Process Control

I right vote the main process as the host, which invokes the child process through the process class, with its ID, which is used. Its calling code is:

private void runtestprocess (bool hidden = false)  {   string appPath = Path.getdirectoryname ( Application.executablepath);   String testapppath = Path.Combine (AppPath, "TestApp.exe");   var pi = new ProcessStartInfo ();   Pi. FileName = Testapppath;   Pi. Arguments = this. Handle.tostring ();   Pi. WindowStyle = hidden? ProcessWindowStyle.Hidden:ProcessWindowStyle.Normal;   this.childprocess = Process.Start (pi);   Txtinfo.text = string. Format ("subprocess id:{0}\r\n child process name: {1}", Childprocess.id, childprocess.processname);   ...  }

The control code is:

private void Btnwork_click (object sender, EventArgs e)  {   if (this.childprocess = = NULL | | this.childProcess.HasExited)    return;   if ((int) Btnwork.tag = = 0)   {    Btnwork.tag = 1;    Btnwork.text = "Recovery";    Processmgr.suspendprocess (this.childProcess.Id);   }   else   {    Btnwork.tag = 0;    Btnwork.text = "hang";    Processmgr.resumeprocess (this.childProcess.Id);   }  }

The child process simulates its work with a timer, throwing progress messages to the main process:

private void Timer_tick (object sender, EventArgs e)  {   if (Progressbar.value < progressbar.maximum)    Progressbar.value + = 1;   else    progressbar.value = 0;   if (this.hosthandle! = IntPtr.Zero)    SendMessage (this.hosthandle, wm_progress, 0, Progressbar.value);  }

The amount of code is so small, simple ...

5.:

For example, there are two diagrams, one showing the child process, and the other is the hidden child process.

The actual project calls the stand-alone process module, which is called in a hidden way, showing its processing progress as a host, as shown in this diagram:

Postscript:

Expansion of ideas, some excellent open source tools, such as YOUTUBE_DL, ffmpeg, etc., are independent processes exist, and can be managed through the CMD communication.

With this process control principle, it is possible to make pretty good GUI tools based on these open source tools. After all, people are easy to do with simple operations, relative to the powerful command line.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.