Process.GetProcessesByName Метод

Определение

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

Перегрузки

GetProcessesByName(String, String)

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

GetProcessesByName(String)

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

GetProcessesByName(String, String)

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

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

Параметры

processName
String

Понятное имя процесса.

machineName
String

Имя компьютера в сети.

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

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

Атрибуты

Исключения

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

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

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

Попытка подключиться к machineName завершилась ошибкой.

-или-

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

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

Примеры

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

#using <System.dll>

using namespace System;
using namespace System::Diagnostics;
using namespace System::ComponentModel;
int main()
{   
   // Get the current process.    
   Process^ currentProcess = Process::GetCurrentProcess();

   // Get all processes running on the local computer.
   array<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.
   array<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.
   array<Process^>^remoteAll = Process::GetProcesses("myComputer");

   // Get all instances of Notepad running on the specific computer, using machine name.
   array<Process^>^remoteByName = Process::GetProcessesByName( "notepad", "myComputer" );
   
   // Get all instances of Notepad running on the specific computer, using IP address.
   array<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" );
}
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();
        }
    }
}
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 компонентов и связать их со всеми ресурсами процесса, которые выполняют один и тот же исполняемый файл на указанном компьютере. Ресурсы процесса уже должны существовать на компьютере, так как GetProcessesByName не создает системные ресурсы, а связывает их с компонентами Process , созданными приложением. Можно processName указать для исполняемого файла, который в настоящее время не выполняется на локальном компьютере, поэтому массив, возвращаемый методом, может быть пустым.

Имя процесса — это понятное имя процесса, например Outlook, которое не включает расширение .exe или путь. GetProcessesByName полезно для получения и управления всеми процессами, связанными с тем же исполняемым файлом. Например, в качестве processName параметра можно передать имя исполняемого файла, чтобы завершить работу всех запущенных экземпляров этого исполняемого файла.

Хотя процесс Id является уникальным для одного ресурса процесса в системе, несколько процессов на локальном компьютере могут запускать приложение, указанное параметром processName . Таким образом, GetProcessById возвращается не более одного процесса, но GetProcessesByName возвращается массив, содержащий все связанные процессы. Если вам нужно управлять процессом с помощью стандартных вызовов API, можно запросить у каждого из этих процессов по очереди его идентификатор. Вы не можете получить доступ к ресурсам процесса только через имя процесса, но после получения массива Process компонентов, связанных с ресурсами процесса, вы можете запускать, завершать и иным образом управлять системными ресурсами.

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

Доступ к процессам на удаленных компьютерах можно получить только для просмотра сведений о процессах, например статистики. Невозможно закрыть, завершить (с помощью Kill) или запустить процессы на удаленных компьютерах.

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

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

GetProcessesByName(String)

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

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

Параметры

processName
String

Понятное имя процесса.

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

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

Атрибуты

Исключения

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

Примеры

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

#using <System.dll>

using namespace System;
using namespace System::Diagnostics;
using namespace System::ComponentModel;
int main()
{   
   // Get the current process.    
   Process^ currentProcess = Process::GetCurrentProcess();

   // Get all processes running on the local computer.
   array<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.
   array<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.
   array<Process^>^remoteAll = Process::GetProcesses("myComputer");

   // Get all instances of Notepad running on the specific computer, using machine name.
   array<Process^>^remoteByName = Process::GetProcessesByName( "notepad", "myComputer" );
   
   // Get all instances of Notepad running on the specific computer, using IP address.
   array<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" );
}
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();
        }
    }
}
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 компонентов и связывания их со всеми ресурсами процесса, которые выполняют один и тот же исполняемый файл на локальном компьютере. Ресурсы процесса уже должны существовать на компьютере, так как GetProcessesByName не создает системные ресурсы, а связывает их с компонентами Process , созданными приложением. Можно processName указать для исполняемого файла, который в настоящее время не выполняется на локальном компьютере, поэтому массив, возвращаемый методом, может быть пустым.

Имя процесса — это понятное имя процесса, например Outlook, которое не включает расширение .exe или путь. GetProcessesByName полезно для получения и управления всеми процессами, связанными с тем же исполняемым файлом. Например, в качестве processName параметра можно передать имя исполняемого файла, чтобы завершить работу всех запущенных экземпляров этого исполняемого файла.

Хотя процесс Id является уникальным для одного ресурса процесса в системе, несколько процессов на локальном компьютере могут запускать приложение, указанное параметром processName . Таким образом, GetProcessById возвращается не более одного процесса, но GetProcessesByName возвращается массив, содержащий все связанные процессы. Если вам нужно управлять процессом с помощью стандартных вызовов API, можно запросить у каждого из этих процессов по очереди его идентификатор. Вы не можете получить доступ к ресурсам процесса только через имя процесса, но после получения массива Process компонентов, связанных с ресурсами процесса, вы можете запускать, завершать и иным образом управлять системными ресурсами.

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

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