Process.GetProcesses Метод

Определение

Создает массив новых Process компонентов и связывает их с существующими ресурсами процесса.

Перегрузки

Имя Описание
GetProcesses()

Создает новый Process компонент для каждого ресурса процесса на локальном компьютере.

GetProcesses(String)

Создает новый Process компонент для каждого ресурса процесса на указанном компьютере.

GetProcesses()

Исходный код:
Process.cs
Исходный код:
Process.cs
Исходный код:
Process.cs
Исходный код:
Process.cs
Исходный код:
Process.cs

Создает новый Process компонент для каждого ресурса процесса на локальном компьютере.

public:
 static cli::array <System::Diagnostics::Process ^> ^ GetProcesses();
[System.Runtime.Versioning.SupportedOSPlatform("maccatalyst")]
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public static System.Diagnostics.Process[] GetProcesses();
public static System.Diagnostics.Process[] GetProcesses();
[<System.Runtime.Versioning.SupportedOSPlatform("maccatalyst")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>]
static member GetProcesses : unit -> System.Diagnostics.Process[]
static member GetProcesses : unit -> System.Diagnostics.Process[]
Public Shared Function GetProcesses () As Process()

Возвращаемое значение

Массив типа Process , представляющий все ресурсы процесса, выполняемые на локальном компьютере.

Атрибуты

Примеры

В следующем примере извлекаются сведения о текущем процессе, процессы, выполняемые на локальном компьютере, все экземпляры Блокнота, запущенные на локальном компьютере, и определенный процесс на локальном компьютере. Затем он извлекает сведения для тех же процессов на удаленном компьютере.

using System;
using System.Diagnostics;
using System.ComponentModel;

namespace MyProcessSample
{
    class MyProcess
    {
        void BindToRunningProcesses()
        {
            // Get the current process.
            Process currentProcess = Process.GetCurrentProcess();

            // Get all processes running on the local computer.
            Process[] localAll = Process.GetProcesses();

            // Get all instances of Notepad running on the local computer.
            // This will return an empty array if notepad isn't running.
            Process[] localByName = Process.GetProcessesByName("notepad");

            // Get a process on the local computer, using the process id.
            // This will throw an exception if there is no such process.
            Process localById = Process.GetProcessById(1234);

            // Get processes running on a remote computer. Note that this
            // and all the following calls will timeout and throw an exception
            // if "myComputer" and 169.0.0.0 do not exist on your local network.

            // Get all processes on a remote computer.
            Process[] remoteAll = Process.GetProcesses("myComputer");

            // Get all instances of Notepad running on the specific computer, using machine name.
            Process[] remoteByName = Process.GetProcessesByName("notepad", "myComputer");

            // Get all instances of Notepad running on the specific computer, using IP address.
            Process[] ipByName = Process.GetProcessesByName("notepad", "169.0.0.0");

            // Get a process on a remote computer, using the process id and machine name.
            Process remoteById = Process.GetProcessById(2345, "myComputer");
        }

        static void Main()
        {
            MyProcess myProcess = new MyProcess();
            myProcess.BindToRunningProcesses();
        }
    }
}
open System.Diagnostics

// Get the current process.
let currentProcess = Process.GetCurrentProcess()

// Get all processes running on the local computer.
let localAll = Process.GetProcesses()

// Get all instances of Notepad running on the local computer.
// This will return an empty array if notepad isn't running.
let localByName = Process.GetProcessesByName "notepad"

// Get a process on the local computer, using the process id.
// This will throw an exception if there is no such process.
let localById = Process.GetProcessById 1234

// Get processes running on a remote computer. Note that this
// and all the following calls will timeout and throw an exception
// if "myComputer" and 169.0.0.0 do not exist on your local network.

// Get all processes on a remote computer.
let remoteAll = Process.GetProcesses "myComputer"

// Get all instances of Notepad running on the specific computer, using machine name.
let remoteByName = Process.GetProcessesByName("notepad", "myComputer")

// Get all instances of Notepad running on the specific computer, using IP address.
let ipByName = Process.GetProcessesByName("notepad", "169.0.0.0")

// Get a process on a remote computer, using the process id and machine name.
let remoteById = Process.GetProcessById(2345, "myComputer")
Imports System.Diagnostics
Imports System.ComponentModel

Namespace MyProcessSample
    Class MyProcess
        Sub BindToRunningProcesses()
            ' Get the current process. You can use currentProcess from this point
            ' to access various properties and call methods to control the process.
            Dim currentProcess As Process = Process.GetCurrentProcess()

            ' Get all processes running on the local computer.
            Dim localAll As Process() = Process.GetProcesses()

            ' Get all instances of Notepad running on the local computer.
            ' This will return an empty array if notepad isn't running.
            Dim localByName As Process() = Process.GetProcessesByName("notepad")

            ' Get a process on the local computer, using the process id.
            ' This will throw an exception if there is no such process.
            Dim localById As Process = Process.GetProcessById(1234)


            ' Get processes running on a remote computer. Note that this
            ' and all the following calls will timeout and throw an exception
            ' if "myComputer" and 169.0.0.0 do not exist on your local network.

            ' Get all processes on a remote computer.
            Dim remoteAll As Process() = Process.GetProcesses("myComputer")

            ' Get all instances of Notepad running on the specific computer, using machine name.
            Dim remoteByName As Process() = Process.GetProcessesByName("notepad", "myComputer")

            ' Get all instances of Notepad running on the specific computer, using IP address.
            Dim ipByName As Process() = Process.GetProcessesByName("notepad", "169.0.0.0")

            ' Get a process on a remote computer, using the process id and machine name.
            Dim remoteById As Process = Process.GetProcessById(2345, "myComputer")
        End Sub

        Shared Sub Main()
            Dim myProcess As New MyProcess()
            myProcess.BindToRunningProcesses()
        End Sub

    End Class

End Namespace 'MyProcessSample

Комментарии

Используйте этот метод, чтобы создать массив новых Process компонентов и связать их со всеми ресурсами процесса на локальном компьютере. Ресурсы процесса уже должны существовать на локальном компьютере, так как GetProcesses не создают системные ресурсы, а связывают ресурсы с компонентами, созданными Process приложением. Так как сама операционная система выполняет фоновые процессы, этот массив никогда не пуст.

Если вы не хотите извлекать все процессы, выполняемые на компьютере, их число можно ограничить с помощью GetProcessById метода или GetProcessesByName метода. GetProcessById Process создает компонент, связанный с процессом, определенным в системе идентификатором процесса, который передается методу. GetProcessesByName создает массив Process компонентов, связанные ресурсы процесса которых совместно используют исполняемый файл, который передается методу.

Note

Несколько служб Windows можно загрузить в одном экземпляре процесса узла службы (svchost.exe). GetProcesses не определяет эти отдельные службы; для этого см GetServices. раздел .

См. также раздел

Применяется к

GetProcesses(String)

Исходный код:
Process.cs
Исходный код:
Process.cs
Исходный код:
Process.cs
Исходный код:
Process.cs
Исходный код:
Process.cs

Создает новый Process компонент для каждого ресурса процесса на указанном компьютере.

public:
 static cli::array <System::Diagnostics::Process ^> ^ GetProcesses(System::String ^ machineName);
[System.Runtime.Versioning.SupportedOSPlatform("maccatalyst")]
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public static System.Diagnostics.Process[] GetProcesses(string machineName);
public static System.Diagnostics.Process[] GetProcesses(string machineName);
[<System.Runtime.Versioning.SupportedOSPlatform("maccatalyst")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>]
static member GetProcesses : string -> System.Diagnostics.Process[]
static member GetProcesses : string -> System.Diagnostics.Process[]
Public Shared Function GetProcesses (machineName As String) As Process()

Параметры

machineName
String

Компьютер, с которого можно считывать список процессов.

Возвращаемое значение

Массив типа Process , представляющий все ресурсы процесса, выполняемые на указанном компьютере.

Атрибуты

Исключения

Недопустимый machineName синтаксис параметра. Она может иметь ноль длины (0).

Параметр machineName имеет значение null.

Платформа операционной системы не поддерживает эту операцию на удаленных компьютерах.

Существуют проблемы с доступом к API счетчика производительности, используемым для получения сведений об обработке. Это исключение относится к Windows NT, Windows 2000 и Windows XP.

Возникла проблема с доступом к базовому системном API.

Примеры

В следующем примере извлекаются сведения о текущем процессе, процессы, выполняемые на локальном компьютере, все экземпляры Блокнота, запущенные на локальном компьютере, и определенный процесс на локальном компьютере. Затем он извлекает сведения для тех же процессов на удаленном компьютере.

using System;
using System.Diagnostics;
using System.ComponentModel;

namespace MyProcessSample
{
    class MyProcess
    {
        void BindToRunningProcesses()
        {
            // Get the current process.
            Process currentProcess = Process.GetCurrentProcess();

            // Get all processes running on the local computer.
            Process[] localAll = Process.GetProcesses();

            // Get all instances of Notepad running on the local computer.
            // This will return an empty array if notepad isn't running.
            Process[] localByName = Process.GetProcessesByName("notepad");

            // Get a process on the local computer, using the process id.
            // This will throw an exception if there is no such process.
            Process localById = Process.GetProcessById(1234);

            // Get processes running on a remote computer. Note that this
            // and all the following calls will timeout and throw an exception
            // if "myComputer" and 169.0.0.0 do not exist on your local network.

            // Get all processes on a remote computer.
            Process[] remoteAll = Process.GetProcesses("myComputer");

            // Get all instances of Notepad running on the specific computer, using machine name.
            Process[] remoteByName = Process.GetProcessesByName("notepad", "myComputer");

            // Get all instances of Notepad running on the specific computer, using IP address.
            Process[] ipByName = Process.GetProcessesByName("notepad", "169.0.0.0");

            // Get a process on a remote computer, using the process id and machine name.
            Process remoteById = Process.GetProcessById(2345, "myComputer");
        }

        static void Main()
        {
            MyProcess myProcess = new MyProcess();
            myProcess.BindToRunningProcesses();
        }
    }
}
open System.Diagnostics

// Get the current process.
let currentProcess = Process.GetCurrentProcess()

// Get all processes running on the local computer.
let localAll = Process.GetProcesses()

// Get all instances of Notepad running on the local computer.
// This will return an empty array if notepad isn't running.
let localByName = Process.GetProcessesByName "notepad"

// Get a process on the local computer, using the process id.
// This will throw an exception if there is no such process.
let localById = Process.GetProcessById 1234

// Get processes running on a remote computer. Note that this
// and all the following calls will timeout and throw an exception
// if "myComputer" and 169.0.0.0 do not exist on your local network.

// Get all processes on a remote computer.
let remoteAll = Process.GetProcesses "myComputer"

// Get all instances of Notepad running on the specific computer, using machine name.
let remoteByName = Process.GetProcessesByName("notepad", "myComputer")

// Get all instances of Notepad running on the specific computer, using IP address.
let ipByName = Process.GetProcessesByName("notepad", "169.0.0.0")

// Get a process on a remote computer, using the process id and machine name.
let remoteById = Process.GetProcessById(2345, "myComputer")
Imports System.Diagnostics
Imports System.ComponentModel

Namespace MyProcessSample
    Class MyProcess
        Sub BindToRunningProcesses()
            ' Get the current process. You can use currentProcess from this point
            ' to access various properties and call methods to control the process.
            Dim currentProcess As Process = Process.GetCurrentProcess()

            ' Get all processes running on the local computer.
            Dim localAll As Process() = Process.GetProcesses()

            ' Get all instances of Notepad running on the local computer.
            ' This will return an empty array if notepad isn't running.
            Dim localByName As Process() = Process.GetProcessesByName("notepad")

            ' Get a process on the local computer, using the process id.
            ' This will throw an exception if there is no such process.
            Dim localById As Process = Process.GetProcessById(1234)


            ' Get processes running on a remote computer. Note that this
            ' and all the following calls will timeout and throw an exception
            ' if "myComputer" and 169.0.0.0 do not exist on your local network.

            ' Get all processes on a remote computer.
            Dim remoteAll As Process() = Process.GetProcesses("myComputer")

            ' Get all instances of Notepad running on the specific computer, using machine name.
            Dim remoteByName As Process() = Process.GetProcessesByName("notepad", "myComputer")

            ' Get all instances of Notepad running on the specific computer, using IP address.
            Dim ipByName As Process() = Process.GetProcessesByName("notepad", "169.0.0.0")

            ' Get a process on a remote computer, using the process id and machine name.
            Dim remoteById As Process = Process.GetProcessById(2345, "myComputer")
        End Sub

        Shared Sub Main()
            Dim myProcess As New MyProcess()
            myProcess.BindToRunningProcesses()
        End Sub

    End Class

End Namespace 'MyProcessSample

Комментарии

Используйте этот метод, чтобы создать массив новых Process компонентов и связать их со всеми ресурсами процесса на указанном (обычно удаленном) компьютере. Ресурсы процесса уже должны существовать на локальном компьютере, так как GetProcesses не создают системные ресурсы, а связывают ресурсы с компонентами, созданными Process приложением. Так как сама операционная система выполняет фоновые процессы, этот массив никогда не пуст.

Если вы не хотите извлекать все процессы, выполняемые на компьютере, их число можно ограничить с помощью GetProcessById метода или GetProcessesByName метода. GetProcessById Process создает компонент, связанный с процессом, определенным в системе идентификатором процесса, который передается методу. GetProcessesByName создает массив Process компонентов, связанные ресурсы процесса которых совместно используют исполняемый файл, который передается методу.

Эта перегрузка GetProcesses метода обычно используется для получения списка ресурсов процесса, работающих на удаленном компьютере в сети, но можно указать локальный компьютер, передав ".".

Note

Несколько служб Windows можно загрузить в одном экземпляре процесса узла службы (svchost.exe). GetProcesses не определяет эти отдельные службы; для этого см GetServices. раздел .

См. также раздел

Применяется к