繁体   English   中英

从“ Windows任务管理器”进程列表中获取项目c#

[英]Get items from “Windows Task Manager” process list c#

我正在尝试从“ 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*/)

        }

    }

我同意评论者的观点,不要重蹈覆辙。 您可以获取流程并进行如下排序:

System.Diagnostics.Process[] myProcs = System.Diagnostics.Process.GetProcesses();

var sorted = myProcs.OrderBy(p => p.UserProcessorTime);

据我了解,user2838881希望获得在Windows机器上对Windows 7中的进程进行排序的方式。 任务管理器运行时,可以通过多种方式对进程进行排序。 由于这个事实,为了使用建议的代码作为答案,他必须找到一种通过编程对任务管理器中的进程进行排序的方法。 完成此操作的一种方法是,可以在删除该过程之前在其代码上添加以下代码行。

        apiSendMessage(lhWndProcessList,LVM_SORTITEMS,0,"0")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM