这里用了ExtractIconEx函数来提取进程的图标
在Process类中添加几个函数:
public Icon GetIconFromExe()
{
IntPtr hLargeIcon = IntPtr.Zero;
IntPtr hSmallIcon = IntPtr.Zero;
string path = this.getFullPath();
try
{
ExtractIconEx(path, 0, ref hLargeIcon, ref hSmallIcon, 1);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
Icon ic = null;
try
{
ic = (Icon)Icon.FromHandle(hSmallIcon).Clone();
}
catch (Exception e)
{
return null;
}
return ic;
}
[DllImport("coredll.dll", CharSet = CharSet.Auto)]
public extern static int GetModuleFileName(uint hModule, StringBuilder strFullPath, int nSize);
[DllImport("coredll.dll", SetLastError = true)]
private static extern IntPtr ExtractIconEx(string fileName, int index, ref IntPtr hIconLarge, ref IntPtr hIconSmall, uint nIcons);
来看一下显示获得的图标,这需要在界面的listView控件中加入imageList
ListViewItem lvi;
listProcess.BeginUpdate();
listProcess.Items.Clear();
ImageList imageListSmall = new ImageList();
int i = 0;
foreach (Process p in processes)
{
lvi = new ListViewItem(p.ProcessName);
Icon ic;
ic = p.GetIconFromExe();
if (ic != null)
{
imageListSmall.Images.Add(ic);
lvi.ImageIndex = i++;
}
String pid = String.Format("{0:x}", p.ProcessId);
lvi.SubItems.Add(pid);
lvi.SubItems.Add(p.ThreadCount.ToString());
listProcess.Items.Add(lvi);
}
listProcess.SmallImageList = imageListSmall;
listProcess.EndUpdate();
}
其中listProcess是一个listView控件的实例