WindowsSignalHandlerRegistration.cs 1.4 KB

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