美好的一天!
我真的需要你的帮助。我试图获取程序检测到的正在运行的应用程序的路径,但每当我单击正在运行的应用程序的特定名称时,它将只返回项目的路径(我编写的Windows应用程序项目)。我很困惑如何解决这个问题。
以下是我的代码:
namespace getting_apps
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.ValueMember != "")
{
textBox1.Text = listBox1.SelectedValue.ToString();
string path;
path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
textBox2.Text = path;
}
if (textBox2.Text == "getting_apps")
{
MessageBox.Show("asldfjasdklfjasdf");
}
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ProcessName");
dt.Columns.Add("ProcessID");
foreach (Process p in Process.GetProcesses("."))
{
try
{
if (p.MainWindowTitle.Length > 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1][0] = p.MainWindowTitle;
dt.Rows[dt.Rows.Count - 1][1] = p.Id.ToString();
}
}
catch { }
}
listBox1.DataSource = dt;
listBox1.DisplayMember = "ProcessName";
listBox1.ValueMember = "ProcessId";
}
}
}
答案 0 :(得分:4)
使用以下代码获取必要的信息:
Process currentProcess = Process.GetCurrentProcess();
Process[] localAll = Process.GetProcesses();
foreach (Process p in localAll)
{
if (p.MainModule != null)
{
int processId = p.Id;
string name = p.MainModule.ModuleName;
string filename = p.MainModule.FileName;
}
}
但是,如果应用程序将在64位操作系统上运行,请将“平台目标”更改为“x64”,并从“属性/构建”窗口中取消选中“首选32位”。
完整代码变为:
private List<ProcessInfoItem> piis = new List<ProcessInfoItem>();
private void Form1_Load(object sender, EventArgs e)
{
piis = GetAllProcessInfos();
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "Id";
listBox1.DataSource = piis;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ProcessInfoItem pii = piis.FirstOrDefault(x => x.Id == (int)(sender as ListBox).SelectedValue);
if (pii != null)
{
MessageBox.Show(pii.FileName);
}
}
private List<ProcessInfoItem> GetAllProcessInfos()
{
List<ProcessInfoItem> result = new List<ProcessInfoItem>();
Process currentProcess = Process.GetCurrentProcess();
Process[] localAll = Process.GetProcesses();
foreach (Process p in localAll)
{
try
{
if (p.Id != 4 && p.Id != 0 && p.MainModule != null)
{
ProcessInfoItem pii = new ProcessInfoItem(p.Id, p.MainModule.ModuleName, p.MainModule.FileName);
result.Add(pii);
}
}
catch (Win32Exception)
{ // Omit "Access is denied" Exception
}
catch (Exception)
{
throw;
}
}
return result;
}
public class ProcessInfoItem
{
public int Id { get; set; }
public string Name { get; set; }
public string FileName { get; set; }
public ProcessInfoItem()
{ }
public ProcessInfoItem(int id, string name, string filename)
{
this.Id = id;
this.Name = name;
this.FileName = filename;
}
}