我正在尝试从“Windows 任务管理器”进程列表中获取所有项目并将它们添加到我的应用程序的列表框中。我找到了获取任务管理器进程列表句柄的代码。而且我有代码使用它的索引从列表中删除一个项目(这是测试我是否拥有正确句柄的好方法)。但我需要 c# 代码来获取进程列表中的项目总数并通过索引获取项目。我会满足于简单地整理所有项目并将它们添加到我的列表框中。
编辑:谢谢你的评论,我会解释更多......我不想只列出进程,否则我会使用:System.Diagnostics.Process.GetProcesses(); 我想按照它们在任务管理器中的排序方式对进程进行排序。任务管理器有多种方法对其进程进行排序。它提供了大约 31 种不同的方法。例如:图像名称、PID、用户名、CPU 使用率等。我的目标是按照它们在任务管理器中的排序顺序获取进程。
static Int32 LVM_FIRST = 4096;
static Int32 LVM_DELETEITEM = (LVM_FIRST + 8);
static Int32 LVM_SORTITEMS = (LVM_FIRST + 48);
[DllImport("user32.dll", EntryPoint = "FindWindowA")]
private static extern Int32 apiFindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowExA")]
private static extern Int32 apiFindWindowEx(Int32 hWnd1, Int32 hWnd2, string lpsz1, string lpsz2);
[DllImport("user32.dll", EntryPoint = "SendMessageA")]
private static extern Int32 apiSendMessage(Int32 hWnd, Int32 wMsg, Int32 wParam, string lParam);
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
private static extern Int32 apiGetDesktopWindow();
void GetItems()
{
Int32 lhWndParent = apiFindWindow(null, "Windows Task Manager");
Int32 lhWndProcessList = 0;
Int32 lhWndDialog = 0;
for (int i = 1; (i <= 7); i++)
{
// Loop through all seven child windows, for handle to the listview
lhWndDialog = apiFindWindowEx(lhWndParent, lhWndDialog, null, null);
if ((lhWndProcessList == 0))
{
lhWndProcessList = apiFindWindowEx(lhWndDialog, 0, "SysListView32", "Processes");
}
}
/* This code removes the first item in the Task Manager Processes list:
* apiSendMessage(lhWndProcessList, LVM_DELETEITEM, 0, "0");
* note that the 3rd paramiter: 0, is the index of the item to delete.
* I put it here in comments because I thought there would be
* something similar to get the name*/
listBox1.Items.Clear();
int TotalItemCount = /*Total item count in Task Manager Processes list*/;
for (int i = 0; i < TotalItemCount; i++)
{
listBox1.Items.Add(/*Get item in Task Manager Processes list by index: i*/)
}
}