LanguageReload.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. namespace UAS_MES_NEW.PublicMethod
  10. {
  11. public class LanguageReload
  12. {
  13. private static readonly object _lock = new object();
  14. private static JObject _root;
  15. private static string _loadedPath;
  16. private static string _defaultCulture = "en-US";
  17. public static void Load(string filePath)
  18. {
  19. lock (_lock)
  20. {
  21. if (!File.Exists(filePath)) throw new FileNotFoundException("Language file not found", filePath);
  22. var text = File.ReadAllText(filePath, System.Text.Encoding.UTF8);
  23. _root = JObject.Parse(text);
  24. _loadedPath = filePath;
  25. // try to read a default culture from file if provided
  26. var metaDefault = _root["meta"]?["defaultCulture"]?.ToString();
  27. if (!string.IsNullOrWhiteSpace(metaDefault)) _defaultCulture = metaDefault;
  28. }
  29. }
  30. public static string GetString(string key, string culture)
  31. {
  32. lock (_lock)
  33. {
  34. if (_root == null) return null;
  35. var node = _root["control"]?[key];
  36. if (node == null) return null;
  37. var v = node[culture]?.ToString();
  38. if (!string.IsNullOrEmpty(v)) return v;
  39. // fallback to default culture
  40. v = node[_defaultCulture]?.ToString();
  41. if (!string.IsNullOrEmpty(v)) return v;
  42. // fallback to any available value
  43. var first = node.Children<JProperty>().FirstOrDefault()?.Value?.ToString();
  44. return first;
  45. }
  46. }
  47. public static void ApplyToControl(Control ctrl, string culture)
  48. {
  49. if (ctrl == null) return;
  50. // For controls that expose Text property
  51. var value = GetString(ctrl.Name, culture);
  52. if (!string.IsNullOrEmpty(value))
  53. {
  54. ctrl.Text = value;
  55. }
  56. // Special handling for ToolStrip / MenuStrip items
  57. if (ctrl is ToolStrip ts)
  58. {
  59. foreach (ToolStripItem item in ts.Items)
  60. {
  61. var v = GetString(item.Name, culture);
  62. if (!string.IsNullOrEmpty(v)) item.Text = v;
  63. }
  64. }
  65. // recursively apply to child controls
  66. foreach (Control child in ctrl.Controls)
  67. {
  68. ApplyToControl(child, culture);
  69. }
  70. }
  71. public static void ApplyToForm(Form form, string culture)
  72. {
  73. if (form == null) return;
  74. // 必须在 InitializeComponent() 之后调用
  75. ApplyToControl(form, culture);
  76. }
  77. public static bool IsLoaded => _root != null;
  78. public static string LoadedPath => _loadedPath;
  79. public static string GetMessage(string key)
  80. {
  81. try
  82. {
  83. var ltObj = BaseUtil.GetCacheData("LanguageType");
  84. var lt = ltObj == null ? "0" : ltObj.ToString();
  85. var culture = lt == "1" ? "en-US" : lt == "2" ? "vi-VN" : "zh-CN";
  86. var s = GetString(key, culture);
  87. if (!string.IsNullOrEmpty(s)) return s;
  88. // 回退到默认文化由 LocalizationProvider 处理,仍未找到则返回 key
  89. return key;
  90. }
  91. catch
  92. {
  93. return key;
  94. }
  95. }
  96. public static string Format(string key, params object[] args)
  97. {
  98. var format = GetMessage(key);
  99. try
  100. {
  101. return string.Format(format, args);
  102. }
  103. catch
  104. {
  105. return format;
  106. }
  107. }
  108. public static void ApplyLocalization(Form form, string culture, string langFilePath = null)
  109. {
  110. if (form == null) return;
  111. try
  112. {
  113. if (!IsLoaded)
  114. {
  115. if (string.IsNullOrEmpty(langFilePath))
  116. throw new InvalidOperationException("语言文件未加载,请传入 langFilePath 或先调用 LocalizationProvider.Load");
  117. Load(langFilePath);
  118. }
  119. // 1. 基本 Text / ToolStrip 项目处理(递归)
  120. ApplyToForm(form, culture);
  121. // 2. 处理 Designer 中声明为字段的 ColumnHeader:按字段名(如 columnHeader1)查找并设置 Text
  122. var formType = form.GetType();
  123. var headerFields = formType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
  124. .Where(f => f.FieldType == typeof(ColumnHeader));
  125. foreach (var f in headerFields)
  126. {
  127. try
  128. {
  129. var header = f.GetValue(form) as ColumnHeader;
  130. if (header == null) continue;
  131. var key = f.Name; // e.g. "columnHeader1"
  132. var txt = GetString(key, culture);
  133. if (!string.IsNullOrEmpty(txt))
  134. {
  135. header.Text = txt;
  136. }
  137. }
  138. catch
  139. {
  140. // 忽略单个列头设置错误
  141. }
  142. }
  143. // 3. 处理控件上的 PlaceHolder / Placeholder 属性(自定义控件)
  144. ApplyPlaceholdersRecursive(form, culture);
  145. // 4. 如果需要,可在此加入对其它特殊控件/属性的处理
  146. }
  147. catch (Exception ex)
  148. {
  149. // 仅做调试输出,生产环境可记录日志
  150. System.Diagnostics.Debug.WriteLine("ApplyLocalization 错误: " + ex.Message);
  151. }
  152. }
  153. private static void ApplyPlaceholdersRecursive(Control parent, string culture)
  154. {
  155. foreach (Control ctrl in parent.Controls)
  156. {
  157. try
  158. {
  159. // 查找 PlaceHolder / Placeholder 属性(大小写兼容)
  160. var prop = ctrl.GetType().GetProperty("PlaceHolder", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
  161. ?? ctrl.GetType().GetProperty("Placeholder", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  162. if (prop != null && prop.CanWrite)
  163. {
  164. // 先尝试按 "控件名.PlaceHolder" 查找占位符翻译
  165. var keyWithProp = $"{ctrl.Name}.PlaceHolder";
  166. var val = GetString(keyWithProp, culture);
  167. if (string.IsNullOrEmpty(val))
  168. {
  169. // 回退到按控件名直接查找
  170. val = GetString(ctrl.Name, culture);
  171. }
  172. if (!string.IsNullOrEmpty(val))
  173. {
  174. prop.SetValue(ctrl, val, null);
  175. }
  176. }
  177. }
  178. catch
  179. {
  180. // 忽略单控件占位符设置错误
  181. }
  182. // 递归子控件
  183. if (ctrl.HasChildren)
  184. {
  185. ApplyPlaceholdersRecursive(ctrl, culture);
  186. }
  187. }
  188. }
  189. }
  190. }