C# 进度的挂起与还原

1. 源起:

依然是模块化编制程序所诱惑的要求。产品首席试行官难侍候,女产品经营更甚之~:p

绝对戏谑,应用方案与制品首席营业官非亲非故,青芋莫怪!

VCU10项目重构,须要各作用模块以单独进程形式完成,比方:音录像调换模块,若以独立进度格局完毕,怎样调节其暂停、继续等职能吗?

线程能够Suspend、Resume,c#嵌入的Process未有此类措施,咋整?

八方受敌疑无路,苦尽甘来十四乡。情到浓时清转薄,此情可待成追思!

前篇描述了经过间数据传递形式,此篇亦以示范演示其间调整与数码交互形式。

 

 

 2、未公开的API函数:NtSuspendProcess、NtResumeProcess

该类函数在MSDN中找不到。

思其原因,概因它们介于Windows API和
内核API之间,威力不容小视。怕二八耙子程序猿滥用而吸引事故,因而密藏。

实际还会有个NtTerminateProcess,因Process有Kill方法,因而可不用。

但再不说的东西,只要有价值,都会被人给翻出来,好酒即使巷子深么!

好,基于其,设计多少个进度管理类,达成模块化编制程序之进程间调整这几个须要。

 

 

3、ProcessMgr

直上代码吧,封装四个进程管理单元:

public static class ProcessMgr
    {
        /// <summary>
        /// The process-specific access rights.
        /// </summary>
        [Flags]
        public enum ProcessAccess : uint
        {
            /// <summary>
            /// Required to terminate a process using TerminateProcess.
            /// </summary>
            Terminate = 0x1,

            /// <summary>
            /// Required to create a thread.
            /// </summary>
            CreateThread = 0x2,

            /// <summary>
            /// Undocumented.
            /// </summary>
            SetSessionId = 0x4,

            /// <summary>
            /// Required to perform an operation on the address space of a process (see VirtualProtectEx and WriteProcessMemory).
            /// </summary>
            VmOperation = 0x8,

            /// <summary>
            /// Required to read memory in a process using ReadProcessMemory.
            /// </summary>
            VmRead = 0x10,

            /// <summary>
            /// Required to write to memory in a process using WriteProcessMemory.
            /// </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 SetProcessWorkingSetSize.
            /// </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 token, 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 has 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类调用子进程,得其ID,以此为用。其调用代码为:

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("子进程ID:{0}\r\n子进程名:{1}", childProcess.Id, childProcess.ProcessName);

            ...
        }

调节代码为:

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 = "恢复";
                ProcessMgr.SuspendProcess(this.childProcess.Id);
            }
            else
            {
                btnWork.Tag = 0;
                btnWork.Text = "挂起";
                ProcessMgr.ResumeProcess(this.childProcess.Id);
            }
        }

子进度以一定时器模拟其行事,向主进度抛进度音信:

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);
        }

5、效果图:

为示范,做了五个图,其一为呈现子进度,其二为隐蔽子进程。

图片 1

实在项目调用独立进程模块,是以隐匿形式调用的,以宿主体现其拍卖速度,如此图:

图片 2

 

 

后记:

庞大思路,一些非凡的开源工具,如youtube_dl、ffmpeg等,都是单独进程格局存在,且可通过CMD管理通讯。

本条进度序调节制原理,能够依据这一个开源工具,做出一定不错的GUI工具出来。毕竟相对于庞大的命令行,大家依旧以简要操作为福利。

相关文章