/MakeWindowFullscreen/ProcessExtensions.cs

https://bitbucket.org/Reivalyn/make-window-fullscreen · C# · 84 lines · 75 code · 9 blank · 0 comment · 10 complexity · 8393c29483283f837b3728372bfe8208 MD5 · raw file

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using MakeWindowFullscreen.WinApi;
  10. namespace MakeWindowFullscreen
  11. {
  12. static class ProcessExtensions
  13. {
  14. public static string GetImageName(this Process process)
  15. {
  16. if (OSVersions.IsQueryFullProcessImageNameSupported)
  17. {
  18. const int SystemIdleProcessId = 0;
  19. if (process.Id == SystemIdleProcessId)
  20. {
  21. return null;
  22. }
  23. IntPtr hprocess = SafeNativeMethods.OpenProcess(ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION, false, process.Id);
  24. if (hprocess == IntPtr.Zero)
  25. {
  26. var errorCode = Marshal.GetLastWin32Error();
  27. const int AccessDeniedErrorCode = 0x5;
  28. if (errorCode == AccessDeniedErrorCode)
  29. {
  30. return null;
  31. }
  32. throw new Win32Exception(errorCode, string.Format("Failed to open process {0}: \"{1}\"", process.Id, process.ProcessName));
  33. }
  34. try
  35. {
  36. int size = 1024;
  37. var buffer = new StringBuilder(size);
  38. if (!SafeNativeMethods.QueryFullProcessImageName(hprocess, 0, buffer, ref size))
  39. {
  40. throw new Win32Exception(Marshal.GetLastWin32Error(), string.Format("Failed to query the image name for process {0}: \"{1}\"", process.Id, process.ProcessName));
  41. }
  42. return buffer.ToString(0, size);
  43. }
  44. finally
  45. {
  46. SafeNativeMethods.CloseHandle(hprocess);
  47. }
  48. }
  49. else
  50. {
  51. try
  52. {
  53. return process.MainModule.FileName;
  54. }
  55. catch (Win32Exception ex)
  56. {
  57. const uint AccessIsDeniedHResult = 0x80004005;
  58. int accessIsDeniedHResult;
  59. unchecked
  60. {
  61. accessIsDeniedHResult = (int)AccessIsDeniedHResult;
  62. }
  63. if (ex.NativeErrorCode == accessIsDeniedHResult)
  64. {
  65. return null;
  66. }
  67. else
  68. {
  69. throw;
  70. }
  71. }
  72. }
  73. }
  74. }
  75. }