ProcessInfoTool.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Drawing;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. namespace Y.Utils.WindowsUtils.ProcessUtils
  9. {
  10. public class ProcessInfoTool
  11. {
  12. #region 程序集信息
  13. struct SHFILEINFO
  14. {
  15. public IntPtr hIcon;
  16. public int iIcon;
  17. public uint dwAttributes;
  18. [MarshalAs(UnmanagedType.LPStr)]
  19. public string szDisplayName;
  20. [MarshalAs(UnmanagedType.LPStr)]
  21. public string szTypeName;
  22. public SHFILEINFO(bool b)
  23. {
  24. this.hIcon = IntPtr.Zero;
  25. this.iIcon = 0;
  26. this.dwAttributes = 0u;
  27. this.szDisplayName = "";
  28. this.szTypeName = "";
  29. }
  30. }
  31. enum SHGFI
  32. {
  33. SmallIcon = 1,
  34. LargeIcon = 0,
  35. Icon = 256,
  36. DisplayName = 512,
  37. Typename = 1024,
  38. SysIconIndex = 16384,
  39. UseFileAttributes = 16
  40. }
  41. #endregion
  42. [DllImport("Shell32.dll")]
  43. static extern int SHGetFileInfo(string pszPath, uint dwFileAttributes, out SHFILEINFO psfi, uint cbfileInfo, SHGFI uFlags);
  44. static Icon GetIcon(string file, bool small)
  45. {
  46. try
  47. {
  48. SHFILEINFO sHFILEINFO = new SHFILEINFO(true);
  49. int cbfileInfo = Marshal.SizeOf(sHFILEINFO);
  50. SHGFI uFlags;
  51. if (small)
  52. {
  53. uFlags = (SHGFI)273;
  54. }
  55. else
  56. {
  57. uFlags = (SHGFI)272;
  58. }
  59. SHGetFileInfo(file, 256u, out sHFILEINFO, (uint)cbfileInfo, uFlags);
  60. return Icon.FromHandle(sHFILEINFO.hIcon);
  61. }
  62. catch { }
  63. return null;
  64. }
  65. public static Icon GetIcon(Process p, bool small)
  66. {
  67. try
  68. {
  69. string fileName = p.MainModule.FileName;
  70. return GetIcon(fileName, small);
  71. }
  72. catch { }
  73. return null;
  74. }
  75. [Obsolete]
  76. public static Icon GetIcon(int pid, bool small)
  77. {
  78. Process p = Process.GetProcessById(pid);
  79. return GetIcon(p, small);
  80. }
  81. [Obsolete]
  82. public static string GetNameById(int pid)
  83. {
  84. string result = "";
  85. try
  86. {
  87. Process processById = Process.GetProcessById(pid);
  88. result = processById.ProcessName;
  89. processById.Close();
  90. }
  91. catch (Exception ex) { }
  92. return result.Trim();
  93. }
  94. }
  95. }