一、新创建一个C#窗体应用程序
二、首先需要在引用中添加对 System.Management.dll 的引用
三、在窗体中添加一个文本框和一个按钮,如下图所示:
四、添加后台代码,如下:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Diagnostics;using System.Management;namespace 获取进程的用户名{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } ////// 通过进程Id来获取进程的用户名 /// /// 进程Id ///private static string GetProcessUserName(int processId) { string name = ""; SelectQuery query = new SelectQuery("select * from Win32_Process where processID=" + processId); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); try { foreach (ManagementObject disk in searcher.Get()) { ManagementBaseObject inPar = null; ManagementBaseObject outPar = null; inPar = disk.GetMethodParameters("GetOwner"); outPar = disk.InvokeMethod("GetOwner", inPar, null); name = outPar["User"].ToString(); break; } } catch { name = "SYSTEM"; } return name; } private void button1_Click(object sender, EventArgs e) { string pName = textBox1.Text; Process[] ps = Process.GetProcessesByName(pName); foreach (Process p in ps) { //弹出进程名和进程的用户名 MessageBox.Show(p.ProcessName + "||" + GetProcessUserName(p.Id)); } } }}
五、这样就能够得到要查询的进程的用户名了!!