HiraganaPhoneticHelper.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace LyricTools
  4. {
  5. public class HiraganaPhoneticHelper : IDisposable
  6. {
  7. private const string ProgId = "MSIME.Japan";
  8. private readonly IFELanguage _instance;
  9. public HiraganaPhoneticHelper()
  10. {
  11. if (!(Activator.CreateInstance(Type.GetTypeFromProgID(ProgId)) is IFELanguage ifelang))
  12. {
  13. throw new Exception($"Could not create object of {ProgId}, is STAThread attribute missing?");
  14. }
  15. var hr = ifelang.Open();
  16. if (hr != 0) throw Marshal.GetExceptionForHR(hr);
  17. hr = ifelang.GetPhonetic("東京は昨日雪が降りました。", 1, -1, out _);
  18. if (hr != 0) throw Marshal.GetExceptionForHR(hr);
  19. _instance = ifelang;
  20. }
  21. public string GetPhonetic(string input)
  22. {
  23. var hr = _instance.GetPhonetic(input, 1, -1, out var result);
  24. if (hr != 0) throw Marshal.GetExceptionForHR(hr);
  25. return result;
  26. }
  27. public void Dispose() => _instance?.Close();
  28. // IFELanguage2 Interface ID
  29. //[Guid("21164102-C24A-11d1-851A-00C04FCC6B14")]
  30. [ComImport]
  31. [Guid("019F7152-E6DB-11d0-83C3-00C04FDDB82E")]
  32. [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  33. private interface IFELanguage
  34. {
  35. int Open();
  36. int Close();
  37. int GetJMorphResult(uint dwRequest, uint dwCMode, int cwchInput, [MarshalAs(UnmanagedType.LPWStr)] string pwchInput, IntPtr pfCInfo, out object ppResult);
  38. int GetConversionModeCaps(ref uint pdwCaps);
  39. int GetPhonetic([MarshalAs(UnmanagedType.BStr)] string @string, int start, int length, [MarshalAs(UnmanagedType.BStr)] out string result);
  40. int GetConversion([MarshalAs(UnmanagedType.BStr)] string @string, int start, int length, [MarshalAs(UnmanagedType.BStr)] out string result);
  41. }
  42. }
  43. }