PageRenderTime 59ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/Wrapper/AutoHotkeyInit.cs

https://github.com/brigand/AhkDll-.NET
C# | 72 lines | 45 code | 6 blank | 21 comment | 4 complexity | 3f44bfa71d3b34c1cc8ce6b9fd058e68 MD5 | raw file
  1. /*
  2. * All code in 'static AutoHotkey()' is taken from here:
  3. * http://stackoverflow.com/questions/666799/embedding-unmanaged-dll-into-a-managed-c-dll/768429#768429
  4. * All credit goes to the author
  5. */
  6. using System;
  7. using System.Reflection;
  8. using System.IO;
  9. namespace AhkWrapper
  10. {
  11. public partial class AutoHotkey
  12. {
  13. static AutoHotkey()
  14. {
  15. if (File.Exists("AutoHotkey.dll"))
  16. {
  17. IntPtr h = Win32.LoadLibrary("AutoHotkey.dll");
  18. return;
  19. }
  20. // Get a temporary directory in which we can store the unmanaged DLL, with
  21. // this assembly's version number in the path in order to avoid version
  22. // conflicts in case two applications are running at once with different versions
  23. string dirName = Path.Combine(Path.GetTempPath(), "AhkWrapper." +
  24. Assembly.GetExecutingAssembly().GetName().Version.ToString());
  25. if (!Directory.Exists(dirName))
  26. Directory.CreateDirectory(dirName);
  27. string dllPath = Path.Combine(dirName, "AutoHotkey.dll");
  28. // Get the embedded resource stream that holds the Internal DLL in this assembly.
  29. // The name looks funny because it must be the default namespace of this project
  30. // (MyAssembly.) plus the name of the Properties subdirectory where the
  31. // embedded resource resides (Properties.) plus the name of the file.
  32. using (Stream stm = Assembly.GetExecutingAssembly().GetManifestResourceStream(
  33. "AhkWrapper.embed.AutoHotkey.dll"))
  34. {
  35. // Copy the assembly to the temporary file
  36. try
  37. {
  38. using (Stream outFile = File.Create(dllPath))
  39. {
  40. const int sz = 4096;
  41. byte[] buf = new byte[sz];
  42. while (true)
  43. {
  44. int nRead = stm.Read(buf, 0, sz);
  45. if (nRead < 1)
  46. break;
  47. outFile.Write(buf, 0, nRead);
  48. }
  49. }
  50. }
  51. catch
  52. {
  53. // This may happen if another process has already created and loaded the file.
  54. // Since the directory includes the version number of this assembly we can
  55. // assume that it's the same bits, so we just ignore the excecption here and
  56. // load the DLL.
  57. }
  58. }
  59. // We must explicitly load the DLL here because the temporary directory
  60. // is not in the PATH.
  61. // Once it is loaded, the DllImport directives that use the DLL will use
  62. // the one that is already loaded into the process.
  63. IntPtr h = Win32.LoadLibrary(dllPath);
  64. }
  65. }
  66. }