Process.GetProcessById Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Создает новый Process компонент и связывает его с указанным ресурсом процесса.
Перегрузки
| Имя | Описание |
|---|---|
| GetProcessById(Int32) |
Возвращает новый Process компонент, учитывая идентификатор процесса на локальном компьютере. |
| GetProcessById(Int32, String) |
Возвращает новый Process компонент, присвоив идентификатор процесса и имя компьютера в сети. |
GetProcessById(Int32)
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
Возвращает новый Process компонент, учитывая идентификатор процесса на локальном компьютере.
public:
static System::Diagnostics::Process ^ GetProcessById(int processId);
public static System.Diagnostics.Process GetProcessById(int processId);
static member GetProcessById : int -> System.Diagnostics.Process
Public Shared Function GetProcessById (processId As Integer) As Process
Параметры
- processId
- Int32
Уникальный системный идентификатор ресурса процесса.
Возвращаемое значение
Компонент Process , связанный с локальным ресурсом процесса, определяемым параметром processId .
Исключения
Процесс, указанный параметром, processId не выполняется. Срок действия идентификатора может быть истек.
Примеры
В следующем примере извлекаются сведения о текущем процессе, процессы, выполняемые на локальном компьютере, все экземпляры Блокнота, запущенные на локальном компьютере, и определенный процесс на локальном компьютере. Затем он извлекает сведения для тех же процессов на удаленном компьютере.
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 компонент и связать его с ресурсом процесса на локальном компьютере. Ресурс процесса уже должен существовать на компьютере, так как GetProcessById(Int32) не создает системный ресурс, а связывает ресурс с компонентом, созданным Process приложением. Процесс Id можно получить только для процесса, который в настоящее время выполняется на компьютере. После завершения процесса создается исключение при GetProcessById(Int32) передаче идентификатора истекшим сроком действия.
На любом конкретном компьютере идентификатор процесса является уникальным.
GetProcessById(Int32) возвращает не более одного процесса. Если вы хотите получить все процессы, работающие с определенным приложением, используйте GetProcessesByName(String). Если на компьютере под управлением указанного приложения существуют несколько процессов, возвращает массив, GetProcessesByName(String) содержащий все связанные процессы. Вы можете запросить каждый из этих процессов, в свою очередь, для его идентификатора. Идентификатор процесса можно просмотреть на панели Processes диспетчера задач Windows. В столбце PID отображается идентификатор процесса, назначенный процессу.
Параметр processId — это Int32 (32-разрядное целое число со знаком), хотя базовый API Windows использует DWORD (целое число без знака без знака) для аналогичных API. Это по историческим причинам.
См. также раздел
Применяется к
GetProcessById(Int32, String)
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
- Исходный код:
- Process.cs
Возвращает новый Process компонент, присвоив идентификатор процесса и имя компьютера в сети.
public:
static System::Diagnostics::Process ^ GetProcessById(int processId, System::String ^ machineName);
public static System.Diagnostics.Process GetProcessById(int processId, string machineName);
static member GetProcessById : int * string -> System.Diagnostics.Process
Public Shared Function GetProcessById (processId As Integer, machineName As String) As Process
Параметры
- processId
- Int32
Уникальный системный идентификатор ресурса процесса.
- machineName
- String
Имя компьютера в сети.
Возвращаемое значение
Компонент Process , связанный с ресурсом удаленного процесса, определяемым параметром processId .
Исключения
Процесс, указанный параметром, processId не выполняется. Срок действия идентификатора может быть истек.
–или–
Недопустимый machineName синтаксис параметра. Имя может иметь нулевую длину (0).
Параметр machineName имеет значение null.
Примеры
В следующем примере извлекаются сведения о текущем процессе, процессы, выполняемые на локальном компьютере, все экземпляры Блокнота, запущенные на локальном компьютере, и определенный процесс на локальном компьютере. Затем он извлекает сведения для тех же процессов на удаленном компьютере.
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 компонент и связать его с ресурсом процесса на удаленном компьютере в сети. Ресурс процесса уже должен существовать на указанном компьютере, так как GetProcessById(Int32, String) не создает системный ресурс, а связывает ресурс с компонентом, созданным Process приложением. Процесс Id можно получить только для процесса, который в настоящее время выполняется на компьютере. После завершения процесса создается исключение при GetProcessById(Int32, String) передаче идентификатора истекшим сроком действия.
На любом конкретном компьютере идентификатор процесса является уникальным.
GetProcessById(Int32, String) возвращает не более одного процесса. Если вы хотите получить все процессы, работающие с определенным приложением, используйте GetProcessesByName(String). Если на компьютере под управлением указанного приложения существуют несколько процессов, возвращает массив, GetProcessesByName(String) содержащий все связанные процессы. Вы можете запросить каждый из этих процессов, в свою очередь, для его идентификатора. Идентификатор процесса можно просмотреть на панели Processes диспетчера задач Windows. В столбце PID отображается идентификатор процесса, назначенный процессу.
Если не указать, используется локальный machineNameкомпьютер. Кроме того, можно указать локальный компьютер, задав machineName значение "." или пустую строку ("").
Параметр processId — это Int32 (32-разрядное целое число со знаком), хотя базовый API Windows использует DWORD (целое число без знака без знака) для аналогичных API. Это по историческим причинам.