WindowsSignalHandlerRegistration.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. namespace ARMeilleure.Signal
  5. {
  6. unsafe class WindowsSignalHandlerRegistration
  7. {
  8. [DllImport("kernel32.dll")]
  9. private static extern IntPtr AddVectoredExceptionHandler(uint first, IntPtr handler);
  10. [DllImport("kernel32.dll")]
  11. private static extern ulong RemoveVectoredExceptionHandler(IntPtr handle);
  12. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
  13. static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName);
  14. [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
  15. private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
  16. private static IntPtr _getCurrentThreadIdPtr;
  17. public static IntPtr RegisterExceptionHandler(IntPtr action)
  18. {
  19. return AddVectoredExceptionHandler(1, action);
  20. }
  21. public static bool RemoveExceptionHandler(IntPtr handle)
  22. {
  23. return RemoveVectoredExceptionHandler(handle) != 0;
  24. }
  25. public static IntPtr GetCurrentThreadIdFunc()
  26. {
  27. if (_getCurrentThreadIdPtr == IntPtr.Zero)
  28. {
  29. IntPtr handle = LoadLibrary("kernel32.dll");
  30. _getCurrentThreadIdPtr = GetProcAddress(handle, "GetCurrentThreadId");
  31. }
  32. return _getCurrentThreadIdPtr;
  33. }
  34. }
  35. }