Process 类

定义

提供对本地和远程进程的访问权限并使你能够启动和停止本地系统进程。

public ref class Process : System::ComponentModel::Component, IDisposable
public ref class Process : IDisposable
public ref class Process : System::ComponentModel::Component
public class Process : System.ComponentModel.Component, IDisposable
public class Process : IDisposable
public class Process : System.ComponentModel.Component
type Process = class
    inherit Component
    interface IDisposable
type Process = class
    interface IDisposable
type Process = class
    inherit Component
Public Class Process
Inherits Component
Implements IDisposable
Public Class Process
Implements IDisposable
Public Class Process
Inherits Component
继承
继承
Process
实现

示例

以下示例使用 类的 Process 实例来启动进程。

#using <System.dll>
using namespace System;
using namespace System::Diagnostics;
using namespace System::ComponentModel;

int main()
{
    Process^ myProcess = gcnew Process;

    try
    {
        myProcess->StartInfo->UseShellExecute = false;
        // You can start any process, HelloWorld is a do-nothing example.
        myProcess->StartInfo->FileName = "C:\\HelloWorld.exe";
        myProcess->StartInfo->CreateNoWindow = true;
        myProcess->Start();
        // This code assumes the process you are starting will terminate itself. 
        // Given that it is started without a window so you cannot terminate it 
        // on the desktop, it must terminate itself or you can do it programmatically
        // from this application using the Kill method.
    }
    catch ( Exception^ e ) 
    {
        Console::WriteLine( e->Message );
    }
}
using System;
using System.Diagnostics;
using System.ComponentModel;

namespace MyProcessSample
{
    class MyProcess
    {
        public static void Main()
        {
            try
            {
                using (Process myProcess = new Process())
                {
                    myProcess.StartInfo.UseShellExecute = false;
                    // You can start any process, HelloWorld is a do-nothing example.
                    myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
                    myProcess.StartInfo.CreateNoWindow = true;
                    myProcess.Start();
                    // This code assumes the process you are starting will terminate itself.
                    // Given that it is started without a window so you cannot terminate it
                    // on the desktop, it must terminate itself or you can do it programmatically
                    // from this application using the Kill method.
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
Imports System.Diagnostics
Imports System.ComponentModel

Namespace MyProcessSample
    Class MyProcess
        Public Shared Sub Main()
            Try
                Using myProcess As New Process()

                    myProcess.StartInfo.UseShellExecute = False
                    ' You can start any process, HelloWorld is a do-nothing example.
                    myProcess.StartInfo.FileName = "C:\\HelloWorld.exe"
                    myProcess.StartInfo.CreateNoWindow = True
                    myProcess.Start()
                    ' This code assumes the process you are starting will terminate itself. 
                    ' Given that it is started without a window so you cannot terminate it 
                    ' on the desktop, it must terminate itself or you can do it programmatically
                    ' from this application using the Kill method.
                End Using
            Catch e As Exception
                Console.WriteLine((e.Message))
            End Try
        End Sub
    End Class
End Namespace

以下示例使用 Process 类本身和静态 Start 方法启动进程。

#using <System.dll>

using namespace System;
using namespace System::Diagnostics;
using namespace System::ComponentModel;

// Opens the Internet Explorer application.
void OpenApplication(String^ myFavoritesPath)
{
    // Start Internet Explorer. Defaults to the home page.
    Process::Start("IExplore.exe");

    // Display the contents of the favorites folder in the browser.
    Process::Start(myFavoritesPath);
}

// Opens urls and .html documents using Internet Explorer.
void OpenWithArguments()
{
    // URLs are not considered documents. They can only be opened
    // by passing them as arguments.
    Process::Start("IExplore.exe", "www.northwindtraders.com");

    // Start a Web page using a browser associated with .html and .asp files.
    Process::Start("IExplore.exe", "C:\\myPath\\myFile.htm");
    Process::Start("IExplore.exe", "C:\\myPath\\myFile.asp");
}

// Uses the ProcessStartInfo class to start new processes,
// both in a minimized mode.
void OpenWithStartInfo()
{
    ProcessStartInfo^ startInfo = gcnew ProcessStartInfo("IExplore.exe");
    startInfo->WindowStyle = ProcessWindowStyle::Minimized;
    Process::Start(startInfo);
    startInfo->Arguments = "www.northwindtraders.com";
    Process::Start(startInfo);
}

int main()
{
    // Get the path that stores favorite links.
    String^ myFavoritesPath = Environment::GetFolderPath(Environment::SpecialFolder::Favorites);
    OpenApplication(myFavoritesPath);
    OpenWithArguments();
    OpenWithStartInfo();
}
using System;
using System.Diagnostics;
using System.ComponentModel;

namespace MyProcessSample
{
    class MyProcess
    {
        // Opens the Internet Explorer application.
        void OpenApplication(string myFavoritesPath)
        {
            // Start Internet Explorer. Defaults to the home page.
            Process.Start("IExplore.exe");

            // Display the contents of the favorites folder in the browser.
            Process.Start(myFavoritesPath);
        }

        // Opens urls and .html documents using Internet Explorer.
        void OpenWithArguments()
        {
            // url's are not considered documents. They can only be opened
            // by passing them as arguments.
            Process.Start("IExplore.exe", "www.northwindtraders.com");

            // Start a Web page using a browser associated with .html and .asp files.
            Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm");
            Process.Start("IExplore.exe", "C:\\myPath\\myFile.asp");
        }

        // Uses the ProcessStartInfo class to start new processes,
        // both in a minimized mode.
        void OpenWithStartInfo()
        {
            ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
            startInfo.WindowStyle = ProcessWindowStyle.Minimized;

            Process.Start(startInfo);

            startInfo.Arguments = "www.northwindtraders.com";

            Process.Start(startInfo);
        }

        static void Main()
        {
            // Get the path that stores favorite links.
            string myFavoritesPath =
                Environment.GetFolderPath(Environment.SpecialFolder.Favorites);

            MyProcess myProcess = new MyProcess();

            myProcess.OpenApplication(myFavoritesPath);
            myProcess.OpenWithArguments();
            myProcess.OpenWithStartInfo();
        }
    }
}
Imports System.Diagnostics
Imports System.ComponentModel

Namespace MyProcessSample
    Class MyProcess
        ' Opens the Internet Explorer application.
        Public Sub OpenApplication(myFavoritesPath As String)
            ' Start Internet Explorer. Defaults to the home page.
            Process.Start("IExplore.exe")

            ' Display the contents of the favorites folder in the browser.
            Process.Start(myFavoritesPath)
        End Sub

        ' Opens URLs and .html documents using Internet Explorer.
        Sub OpenWithArguments()
            ' URLs are not considered documents. They can only be opened
            ' by passing them as arguments.
            Process.Start("IExplore.exe", "www.northwindtraders.com")

            ' Start a Web page using a browser associated with .html and .asp files.
            Process.Start("IExplore.exe", "C:\myPath\myFile.htm")
            Process.Start("IExplore.exe", "C:\myPath\myFile.asp")
        End Sub

        ' Uses the ProcessStartInfo class to start new processes,
        ' both in a minimized mode.
        Sub OpenWithStartInfo()
            Dim startInfo As New ProcessStartInfo("IExplore.exe")
            startInfo.WindowStyle = ProcessWindowStyle.Minimized

            Process.Start(startInfo)

            startInfo.Arguments = "www.northwindtraders.com"

            Process.Start(startInfo)
        End Sub

        Shared Sub Main()
            ' Get the path that stores favorite links.
            Dim myFavoritesPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Favorites)

            Dim myProcess As New MyProcess()

            myProcess.OpenApplication(myFavoritesPath)
            myProcess.OpenWithArguments()
            myProcess.OpenWithStartInfo()
        End Sub
    End Class
End Namespace 'MyProcessSample

下面的 F# 示例定义一个 runProc 函数,该函数启动进程,捕获所有输出和错误信息,并记录进程已运行的毫秒数。 该 runProc 函数有三个参数:要启动的应用程序的名称、要提供给应用程序的参数和起始目录。

open System
open System.Diagnostics

let runProc filename args startDir : seq<string> * seq<string> = 
    let timer = Stopwatch.StartNew()
    let procStartInfo = 
        ProcessStartInfo(
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            FileName = filename,
            Arguments = args
        )
    match startDir with | Some d -> procStartInfo.WorkingDirectory <- d | _ -> ()

    let outputs = System.Collections.Generic.List<string>()
    let errors = System.Collections.Generic.List<string>()
    let outputHandler f (_sender:obj) (args:DataReceivedEventArgs) = f args.Data
    use p = new Process(StartInfo = procStartInfo)
    p.OutputDataReceived.AddHandler(DataReceivedEventHandler (outputHandler outputs.Add))
    p.ErrorDataReceived.AddHandler(DataReceivedEventHandler (outputHandler errors.Add))
    let started = 
        try
            p.Start()
        with | ex ->
            ex.Data.Add("filename", filename)
            reraise()
    if not started then
        failwithf "Failed to start process %s" filename
    printfn "Started %s with pid %i" p.ProcessName p.Id
    p.BeginOutputReadLine()
    p.BeginErrorReadLine()
    p.WaitForExit()
    timer.Stop()
    printfn "Finished %s after %A milliseconds" filename timer.ElapsedMilliseconds
    let cleanOut l = l |> Seq.filter (fun o -> String.IsNullOrEmpty o |> not)
    cleanOut outputs,cleanOut errors

函数的代码 runProcImaginaryDevelopment 编写,在 Microsoft 公共许可证下提供。

注解

Process组件提供对计算机上正在运行的进程的访问权限。 用最简单的术语说,进程是一个正在运行的应用。 线程是操作系统分配处理器时间的基本单元。 线程可以执行进程代码的任何部分,包括当前由另一个线程执行的部分。

组件 Process 是用于启动、停止、控制和监视应用的有用工具。 可以使用 Process 组件获取正在运行的进程的列表,也可以启动新进程。 组件 Process 用于访问系统进程。 Process组件初始化后,它可用于获取有关正在运行的进程的信息。 此类信息包括线程集、加载的模块 (.dll 和 .exe 文件) ,以及进程正在使用的内存量等性能信息。

此类型实现 IDisposable 接口。 在使用完类型后,您应直接或间接释放类型。 若要直接释放类型,请在 try/finally 块中调用其 Dispose 方法。 若要间接释放类型,请使用 using(在 C# 中)或 Using(在 Visual Basic 中)等语言构造。 有关详细信息,请参阅接口文档中的“使用实现 IDisposable 的对象”部分 IDisposable

重要

使用不受信任的数据调用此类中的方法存在安全风险。 仅使用受信任的数据调用此类中的方法。 有关详细信息,请参阅 验证所有输入

注意

32 位进程无法访问 64 位进程的模块。 如果尝试从 32 位进程获取有关 64 位进程的信息,则会出现异常 Win32Exception 。 另一方面,64 位进程可以访问 32 位进程的模块。

进程组件一次获取有关一组属性的信息。 在 Process 组件获取有关任何组的一个成员的信息后,它将缓存该组中其他属性的值,并且不会获取有关组其他成员的新信息,直到调用 Refresh 方法。 因此,不保证属性值比上次调用 Refresh 方法更新。 组细分取决于操作系统。

如果在系统中使用引号声明了路径变量,则必须在启动在该位置找到的任何进程时完全限定该路径。 否则,系统将找不到路径。 例如,如果 c:\mypath 路径中没有 ,并且使用引号添加它: path = %path%;"c:\mypath",则必须在启动时完全限定中的任何 c:\mypath 进程。

系统进程通过其进程标识符在系统上唯一标识。 与许多 Windows 资源一样,进程也由其句柄标识,该句柄在计算机上可能不是唯一的。 句柄是资源标识符的泛型术语。 操作系统保留进程句柄,即使进程已退出,也可以通过 Handle 组件的 属性 Process 访问该句柄。 因此,可以获取进程的管理信息,例如 ExitCode (通常为零表示成功,或者) 和 ExitTime的非零错误代码。 句柄是一种极其有价值的资源,因此泄漏句柄比泄漏内存更严重。

注意

此类包含应用于所有成员的类级别的链接需求和继承需求。 SecurityException当直接调用方或派生类没有完全信任权限时,将引发 。 有关安全要求的详细信息,请参阅 链接需求

.NET Core 说明

在 .NET Framework 中Process, 类默认对输入、输出和错误流使用Console编码(通常为代码页编码)。 例如,在区域性为英语 (美国) 的系统上,代码页 437 是 类的默认编码Console。 但是,.NET Core 可能只提供这些编码的有限子集。 如果是这种情况,则使用 Encoding.UTF8 作为默认编码。

Process如果 对象依赖于特定的代码页编码,则仍然可以在调用任何Process方法之前执行以下操作来使其可用:

  1. EncodingProvider从 属性中CodePagesEncodingProvider.Instance检索 对象。

  2. EncodingProvider 对象传递给 Encoding.RegisterProvider 方法,使编码提供程序支持的其他编码可用。

然后, Process 类将自动使用默认系统编码而不是 UTF8,前提是在调用任何 Process 方法之前已注册编码提供程序。

构造函数

Process()

初始化 Process 类的新实例。

属性

BasePriority

获取关联进程的基本优先级。

CanRaiseEvents

获取一个指示组件是否可以引发事件的值。

(继承自 Component)
Container

获取包含 IContainerComponent

(继承自 Component)
DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。

(继承自 Component)
EnableRaisingEvents

获取或设置在进程终止时是否应引发 Exited 事件。

Events

获取附加到此 Component 的事件处理程序的列表。

(继承自 Component)
ExitCode

获取关联进程终止时指定的值。

ExitTime

获取关联进程退出的时间。

Handle

获取关联进程的本机句柄。

HandleCount

获取由进程打开的句柄数。

HasExited

获取指示关联进程是否已终止的值。

Id

获取关联进程的唯一标识符。

MachineName

获取关联进程正在其上运行的计算机的名称。

MainModule

获取关联进程的主模块。

MainWindowHandle

获取关联进程主窗口的窗口句柄。

MainWindowTitle

获取进程的主窗口标题。

MaxWorkingSet

获取或设置关联进程允许的最大工作集大小(以字节为单位)。

MinWorkingSet

获取或设置关联进程允许的最小工作集大小(以字节为单位)。

Modules

获取已由关联进程加载的模块。

NonpagedSystemMemorySize
已过时.
已过时.
已过时.

获取为关联的进程分配的非分页系统内存量(以字节为单位)。

NonpagedSystemMemorySize64

获取为关联的进程分配的非分页系统内存量(以字节为单位)。

PagedMemorySize
已过时.
已过时.
已过时.

获取为关联的进程分配的分页内存量(以字节为单位)。

PagedMemorySize64

获取为关联的进程分配的分页内存量(以字节为单位)。

PagedSystemMemorySize
已过时.
已过时.
已过时.

获取为关联进程分配的可分页系统内存量(以字节为单位)。

PagedSystemMemorySize64

获取为关联进程分配的可分页系统内存量(以字节为单位)。

PeakPagedMemorySize
已过时.
已过时.
已过时.

获取关联的进程使用的虚拟内存分页文件中的最大内存量(以字节为单位)。

PeakPagedMemorySize64

获取关联的进程使用的虚拟内存分页文件中的最大内存量(以字节为单位)。

PeakVirtualMemorySize
已过时.
已过时.
已过时.

获取关联进程使用的最大虚拟内存量(以字节为单位)。

PeakVirtualMemorySize64

获取关联进程使用的最大虚拟内存量(以字节为单位)。

PeakWorkingSet
已过时.
已过时.
已过时.

获取关联进程的峰值工作集大小(以字节为单位)。

PeakWorkingSet64

获取关联进程使用的最大物理内存量(以字节为单位)。

PriorityBoostEnabled

获取或设置一个值,该值指示主窗口拥有焦点时是否应由操作系统暂时提升关联进程优先级。

PriorityClass

获取或设置关联进程的总体优先级类别。

PrivateMemorySize
已过时.
已过时.
已过时.

获取为关联的进程分配的专用内存量(以字节为单位)。

PrivateMemorySize64

获取为关联的进程分配的专用内存量(以字节为单位)。

PrivilegedProcessorTime

获取此进程的特权处理器时间。

ProcessName

获取该进程的名称。

ProcessorAffinity

获取或设置一些处理器,此进程中的线程可以按计划在这些处理器上运行。

Responding

获取指示进程的用户界面当前是否响应的值。

SafeHandle

获取此进程的本机句柄。

SessionId

获取关联进程的终端服务会话标识符。

Site

获取或设置 ComponentISite

(继承自 Component)
StandardError

获取用于读取应用程序错误输出的流。

StandardInput

获取用于写入应用程序输入的流。

StandardOutput

获取用于读取应用程序文本输出的流。

StartInfo

获取或设置要传递给 Start()Process 方法的属性。

StartTime

获取关联进程启动的时间。

SynchronizingObject

获取或设置用于封送由于进程退出事件而发出的事件处理程序调用的对象。

Threads

获取在关联进程中运行的一组线程。

TotalProcessorTime

获取此进程的总的处理器时间。

UserProcessorTime

获取此进程的用户处理器时间。

VirtualMemorySize
已过时.
已过时.
已过时.

获取进程的虚拟内存大小(以字节为单位)。

VirtualMemorySize64

获取为关联进程分配的虚拟内存量(以字节为单位)。

WorkingSet
已过时.
已过时.
已过时.

获取关联进程的物理内存使用量(以字节为单位)。

WorkingSet64

获取为关联的进程分配的物理内存量(以字节为单位)。

方法

BeginErrorReadLine()

在应用程序的重定向 StandardError 流上开始进行异步读取操作。

BeginOutputReadLine()

在应用程序的重定向 StandardOutput 流上开始进行异步读取操作。

CancelErrorRead()

取消在应用程序的重定向 StandardError 流上执行的异步读取操作。

CancelOutputRead()

取消在应用程序的重定向 StandardOutput 流上执行的异步读取操作。

Close()

释放与此组件关联的所有资源。

CloseMainWindow()

通过向进程的主窗口发送关闭消息来关闭拥有用户界面的进程。

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。

(继承自 MarshalByRefObject)
Dispose()

执行与释放或重置非托管资源关联的应用程序定义的任务。

Dispose()

释放由 Component 使用的所有资源。

(继承自 Component)
Dispose(Boolean)

释放此进程使用的所有资源。

EnterDebugMode()

通过启用当前线程的本机属性 Process,将 SeDebugPrivilege 组件置于与以特殊模式运行的操作系统进程交互的状态。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetCurrentProcess()

获取新的 Process 组件并将其与当前活动的进程关联。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时.

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetProcessById(Int32)

返回新的 Process 组件(给定本地计算机上某个进程的标识符)。

GetProcessById(Int32, String)

返回新的 Process 组件(给定进程标识符和网络中计算机的名称)。

GetProcesses()

为本地计算机上的每个进程资源创建一个新的 Process 组件。

GetProcesses(String)

为指定计算机上的每个进程资源创建一个新的 Process 组件。

GetProcessesByName(String)

创建新的 Process 组件的数组,并将它们与本地计算机上共享指定的进程名称的所有进程资源关联。

GetProcessesByName(String, String)

创建新的 Process 组件的数组,并将它们与远程计算机上共享指定进程名称的所有进程资源关联。

GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。

(继承自 Component)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
Kill()

立即停止关联的进程。

Kill(Boolean)

立即停止关联的进程,并可选择停止其子/后代进程。

LeaveDebugMode()

使 Process 组件离开允许它与以特殊模式运行的操作系统进程交互的状态。

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
OnExited()

引发 Exited 事件。

Refresh()

放弃已缓存到进程组件的关联仅存的任何相关信息。

Start()

启动(或重用)此 Process 组件的 StartInfo 属性指定的进程资源,并将其与该组件关联。

Start(ProcessStartInfo)

启动由包含进程启动信息(例如,要启动的进程的文件名)的参数指定的进程资源,并将该资源与新的 Process 组件关联。

Start(String)

通过指定文档或应用程序文件的名称来启动进程资源,并将资源与新的 Process 组件关联。

Start(String, IEnumerable<String>)

通过指定应用程序的名称和一组命令行参数来启动一个进程资源。

Start(String, String)

通过指定应用程序的名称和一组命令行参数来启动一个进程资源,并将该资源与新的 Process 组件相关联。

Start(String, String, SecureString, String)

通过指定应用程序的名称、用户名、密码和域来启动一个进程资源,并将该资源与新的 Process 组件关联起来。

Start(String, String, String, SecureString, String)

通过指定应用程序的名称、一组命令行自变量、用户名、密码和域来启动一个进程资源,并将该资源与新的 Process 组件关联起来。

ToString()

如果适用,则将进程的名称格式化为字符串,并与父组件类型组合。

ToString()

返回表示当前对象的字符串。

(继承自 Object)
WaitForExit()

指示 Process 组件无限期地等待关联进程退出。

WaitForExit(Int32)

指示 Process 组件在指定的毫秒数内等待关联进程退出。

WaitForExit(TimeSpan)

指示进程组件等待指定的时间量,使关联的进程退出。

WaitForExitAsync(CancellationToken)

指示进程组件等待关联进程退出,或指示等待 cancellationToken 被取消。

WaitForInputIdle()

使 Process 组件无限期地等待关联进程进入空闲状态。 此重载仅适用于具有用户界面并因此具有消息循环的进程。

WaitForInputIdle(Int32)

使 Process 组件在指定的毫秒数内等待关联进程进入空闲状态。 此重载仅适用于具有用户界面并因此具有消息循环的进程。

WaitForInputIdle(TimeSpan)

Process使组件等待指定的 timeout ,以便关联的进程进入空闲状态。 此重载仅适用于具有用户界面并因此具有消息循环的进程。

事件

Disposed

在通过调用 Dispose() 方法释放组件时发生。

(继承自 Component)
ErrorDataReceived

当应用程序写入其重定向 StandardError 流中时发生。

Exited

在进程退出时发生。

OutputDataReceived

每次应用程序向其重定向 StandardOutput 流中写入行时发生。

适用于

另请参阅