Process.GetProcessesByName Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Создает массив новых Process компонентов и связывает их с существующими ресурсами процесса, которые используют указанное имя процесса.
Перегрузки
| Имя | Описание |
|---|---|
| GetProcessesByName(String) |
Создает массив новых Process компонентов и связывает их со всеми ресурсами процесса на локальном компьютере, которым предоставляется общий доступ к указанному имени процесса. |
| GetProcessesByName(String, String) |
Создает массив новых Process компонентов и связывает их со всеми ресурсами процесса на удаленном компьютере, который использует указанное имя процесса. |
GetProcessesByName(String)
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
Создает массив новых Process компонентов и связывает их со всеми ресурсами процесса на локальном компьютере, которым предоставляется общий доступ к указанному имени процесса.
public:
static cli::array <System::Diagnostics::Process ^> ^ GetProcessesByName(System::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);
public static System.Diagnostics.Process[] GetProcessesByName(string processName);
[<System.Runtime.Versioning.SupportedOSPlatform("maccatalyst")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>]
static member GetProcessesByName : string -> System.Diagnostics.Process[]
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;
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 компонентов и связать их со всеми ресурсами процесса, выполняющими один исполняемый файл на локальном компьютере. Ресурсы процесса уже должны существовать на компьютере, так как GetProcessesByName не создают системные ресурсы, а связывают их с компонентами, созданными Process приложением.
processName Можно указать исполняемый файл, который в настоящее время не запущен на локальном компьютере, поэтому массив, возвращаемый методом, может быть пустым.
Имя процесса — это понятное имя процесса, например Outlook, которое не включает расширение .exe или путь.
GetProcessesByName полезно для получения и управления всеми процессами, связанными с одинаковым исполняемым файлом. Например, можно передать имя исполняемого файла в качестве processName параметра, чтобы завершить работу всех запущенных экземпляров этого исполняемого файла.
Хотя процесс Id является уникальным для одного ресурса процесса в системе, несколько процессов на локальном компьютере могут запускать приложение, указанное параметром processName . Таким образом, GetProcessById возвращает один процесс в большинстве случаев, но GetProcessesByName возвращает массив, содержащий все связанные процессы. Если вам нужно управлять процессом с помощью стандартных вызовов API, можно запросить каждый из этих процессов в свою очередь для его идентификатора. Доступ к ресурсам процесса нельзя получить только через имя процесса, но после получения массива Process компонентов, связанных с ресурсами процесса, можно запустить, завершить работу и в противном случае управлять системными ресурсами.
См. также раздел
Применяется к
GetProcessesByName(String, String)
- Исходный код:
- Process.Linux.cs
- Исходный код:
- Process.cs
- Исходный код:
- Process.Linux.cs
- Исходный код:
- Process.Linux.cs
- Исходный код:
- Process.Linux.cs
Создает массив новых Process компонентов и связывает их со всеми ресурсами процесса на удаленном компьютере, который использует указанное имя процесса.
public:
static cli::array <System::Diagnostics::Process ^> ^ GetProcessesByName(System::String ^ processName, System::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);
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")>]
static member GetProcessesByName : string * string -> System.Diagnostics.Process[]
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;
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 компонентов и связать их со всеми ресурсами процесса, выполняющими один исполняемый файл на указанном компьютере. Ресурсы процесса уже должны существовать на компьютере, так как GetProcessesByName не создают системные ресурсы, а связывают их с компонентами, созданными Process приложением.
processName Можно указать исполняемый файл, который в настоящее время не запущен на локальном компьютере, поэтому массив, возвращаемый методом, может быть пустым.
Имя процесса — это понятное имя процесса, например Outlook, которое не включает расширение .exe или путь.
GetProcessesByName полезно для получения и управления всеми процессами, связанными с одинаковым исполняемым файлом. Например, можно передать имя исполняемого файла в качестве processName параметра, чтобы завершить работу всех запущенных экземпляров этого исполняемого файла.
Хотя процесс Id является уникальным для одного ресурса процесса в системе, несколько процессов на локальном компьютере могут запускать приложение, указанное параметром processName . Таким образом, GetProcessById возвращает один процесс в большинстве случаев, но GetProcessesByName возвращает массив, содержащий все связанные процессы. Если вам нужно управлять процессом с помощью стандартных вызовов API, можно запросить каждый из этих процессов в свою очередь для его идентификатора. Доступ к ресурсам процесса нельзя получить только через имя процесса, но после получения массива Process компонентов, связанных с ресурсами процесса, можно запустить, завершить работу и в противном случае управлять системными ресурсами.
Эту перегрузку можно использовать для получения процессов на локальном компьютере, а также на удаленном компьютере. Используйте "." для указания локального компьютера. Другая перегрузка существует, которая использует локальный компьютер по умолчанию.
Доступ к процессам на удаленных компьютерах можно получить только для просмотра сведений, таких как статистика, о процессах. Невозможно закрыть, завершить (с помощью Kill) или запустить процессы на удаленных компьютерах.