ProcessInfoTool.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 Azylee.Core.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. Icon ic = GetIcon(p, small);
  80. p.Close();
  81. return ic;
  82. }
  83. [Obsolete]
  84. public static string GetNameById(int pid)
  85. {
  86. string result = "";
  87. try
  88. {
  89. Process processById = Process.GetProcessById(pid);
  90. result = processById.ProcessName;
  91. processById.Close();
  92. }
  93. catch (Exception ex) { }
  94. return result.Trim();
  95. }
  96. }
  97. }