1. 程式人生 > >獲取新的 Process 元件並將其與當前活動的程序關聯

獲取新的 Process 元件並將其與當前活動的程序關聯

using System.Diagnostics;

namespace Test1
{
    class MyProcess
    {
        void BindToRunningProcesses()
        {
            // 獲取當前程序。
            Process currentProcess = Process.GetCurrentProcess();

            //獲取在本地計算機上執行的所有程序。
            Process[] localAll = Process.GetProcesses();

            // 獲取在本地計算機上執行的所有記事本例項。
            // 如果記事本沒有執行, 這將返回空陣列。
            Process[] localByName = Process.GetProcessesByName("notepad");

            // 使用程序 id 獲取本地計算機上的程序。
            // 如果沒有這樣的程序, 這將引發異常。
            Process localById = Process.GetProcessById(1234);


            //獲取在遠端計算機上執行的程序。注意, 此
            //下面的所有呼叫都將超時並引發異常
            //如果本地網路上不存在  "myComputer " 和169.0.0.0。

            //獲取遠端計算機上的所有程序。
            Process[] remoteAll = Process.GetProcesses("myComputer");

            //使用計算機名稱獲取在特定計算機上執行的所有記事本例項。
            Process[] remoteByName = Process.GetProcessesByName("notepad", "myComputer");

            // 使用 IP 地址獲取在特定計算機上執行的所有記事本例項。
            Process[] ipByName = Process.GetProcessesByName("notepad", "169.0.0.0");

            // 使用程序 id 和計算機名稱獲取遠端計算機上的程序。
            Process remoteById = Process.GetProcessById(2345, "myComputer");
        }

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