Process.GetProcessById Метод

Определение

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

Перегрузки

GetProcessById(Int32)

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

GetProcessById(Int32, String)

Возвращает новый компонент Process по заданному идентификатору процесса и имени компьютера в сети.

GetProcessById(Int32)

Исходный код:
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.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 компонент и связать его с ресурсом процесса на локальном компьютере. Ресурс процесса уже должен существовать на компьютере, так как GetProcessById(Int32) не создает системный ресурс, а связывает ресурс с компонентом, созданным приложением Process . Процесс Id может быть получен только для процесса, который в настоящее время выполняется на компьютере. После завершения процесса вызывает исключение, GetProcessById(Int32) если вы передаете ему идентификатор с истекшим сроком действия.

На любом конкретном компьютере идентификатор процесса уникален. GetProcessById(Int32) возвращает не более одного процесса. Если вы хотите получить все процессы, выполняющих определенное приложение, используйте .GetProcessesByName(String) Если на компьютере, на котором выполняется указанное приложение, существует несколько процессов, возвращает массив, GetProcessesByName(String) содержащий все связанные процессы. Вы можете запросить у каждого из этих процессов по очереди его идентификатор. Идентификатор процесса можно просмотреть на Processes панели диспетчера задач Windows. В столбце PID отображается идентификатор процесса, назначенный процессу.

Параметр processId является Int32 (32-разрядное целое число со знаком), хотя базовый API Windows использует DWORD (32-разрядное целое число без знака) для аналогичных API. Это связано с историческими причинами.

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

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

GetProcessById(Int32, String)

Исходный код:
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.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 компонент и связать его с ресурсом процесса на удаленном компьютере в сети. Ресурс процесса уже должен существовать на указанном компьютере, так как 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 (32-разрядное целое число без знака) для аналогичных API. Это связано с историческими причинами.

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

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