我如何添加到listBox1所有的进程名称,也每个进程图标附近,就像在任务管理器

本文关键字:进程 图标 任务管理器 进程名 添加 何添加 listBox1 | 更新日期: 2023-09-27 18:06:01

Process[] processlist = Process.GetProcesses();
            foreach (Process theprocess in processlist)
            {
                listBox1.Items.Add(theprocess.ProcessName);
                icons.Add(Icon.ExtractAssociatedIcon(theprocess.MainModule.FileName));
            }

这样我将所有进程添加到listBox1.

但是我得到异常访问拒绝(我在admin权限下,我运行visual studio作为admin):

icons.Add(Icon.ExtractAssociatedIcon(theprocess.MainModule.FileName));

Win32Exception: Access is denied

System.ComponentModel.Win32Exception was unhandled
  HResult=-2147467259
  Message=Access is denied
  Source=System
  ErrorCode=-2147467259
  NativeErrorCode=5
  StackTrace:
       at System.Diagnostics.ProcessManager.OpenProcess(Int32 processId, Int32 access, Boolean throwIfExited)
       at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly)
       at System.Diagnostics.NtProcessManager.GetFirstModuleInfo(Int32 processId)
       at System.Diagnostics.Process.get_MainModule()
       at HardwareMonitoring.Form1..ctor() in d:'C-Sharp'HardwareMonitoring'HardwareMonitoring'Hardwaremonitoring'Form1.cs:line 124
       at HardwareMonitoring.Program.Main() in d:'C-Sharp'HardwareMonitoring'HardwareMonitoring'Hardwaremonitoring'Program.cs:line 17
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

我想做的是在listBox1中列出所有进程,并在每个进程的右侧显示它的徽标。就像在windows任务管理器中显示的那样。

我如何添加到listBox1所有的进程名称,也每个进程图标附近,就像在任务管理器

您的代码应该工作-除非a)没有关联的Icon,如Dan-o所说的或b)您尝试从32位进程访问64位进程。只需在违规行周围放置一个try,并在catching周围放置一个默认的Icon就可以解决问题。

所以,这或多或少就是你所拥有的,与catch子句和一个自定义类用于ListBox:

// a class to work with the listbox:
class proc
{
    public Process process { get; set; }
    public proc (Process process_) {process = process_;}
    public override string ToString() { return process.MainWindowTitle; }
}

// a button-click to fill/refresh the list:
private void cb_refresh_Click(object sender, EventArgs e)
{
    lb_processes.Items.Clear();
    var allProcceses = Process.GetProcesses();
    foreach (Process process in allProcceses)
    {
        if (!string.IsNullOrEmpty(process.MainWindowTitle))
            lb_processes.Items.Add(new proc(process));
    }
}

// the event to display the icon:
private void lb_processes_SelectedIndexChanged(object sender, EventArgs e)
{
    Process p = ((proc)lb_processes.SelectedItem).process;
    // the process list is cached -> refresh & leave if a process has ended!  
    if (p.HasExited)
    {
        MessageBox.Show("This process has exited!", p.MainWindowTitle);
        cb_refresh_Click(null, null);
        return;
    }
    try
    {
        pb_icon.Image = Icon.ExtractAssociatedIcon(p.MainModule.FileName).ToBitmap(); 
    } 
    catch (Exception ex) 
    { 
      // expected errors if there is no icon or the process is 64-bit
      if (ex is ArgumentException || ex is Win32Exception )
      {
        pb_icon.Image = pb_icon.Image = Bitmap.FromHicon(SystemIcons.Application.Handle); 
      }
      else
      {
        pb_icon.Image = pb_icon.Image = Bitmap.FromHicon(SystemIcons.Error.Handle); 
        throw;
      }
    }

Edit:根据建议增加了改进的错误检查。}