DisableMediaInsertionPrompt.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. #if MS_IO_REDIST
  5. using System;
  6. namespace Microsoft.IO
  7. #else
  8. namespace System.IO
  9. #endif
  10. {
  11. /// <summary>
  12. /// Simple wrapper to safely disable the normal media insertion prompt for
  13. /// removable media (floppies, cds, memory cards, etc.)
  14. /// </summary>
  15. /// <remarks>
  16. /// Note that removable media file systems lazily load. After starting the OS
  17. /// they won't be loaded until you have media in the drive- and as such the
  18. /// prompt won't happen. You have to have had media in at least once to get
  19. /// the file system to load and then have removed it.
  20. /// </remarks>
  21. internal struct DisableMediaInsertionPrompt : IDisposable
  22. {
  23. private bool _disableSuccess;
  24. private uint _oldMode;
  25. public static DisableMediaInsertionPrompt Create()
  26. {
  27. DisableMediaInsertionPrompt prompt = new DisableMediaInsertionPrompt();
  28. prompt._disableSuccess = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out prompt._oldMode);
  29. return prompt;
  30. }
  31. public void Dispose()
  32. {
  33. uint ignore;
  34. if (_disableSuccess)
  35. Interop.Kernel32.SetThreadErrorMode(_oldMode, out ignore);
  36. }
  37. }
  38. }