RequestHandler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. using CefSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Drawing;
  5. using System.Text.RegularExpressions;
  6. using System.Windows.Forms;
  7. namespace UAS_Web.tool
  8. {
  9. class RequestHandler : IRequestHandler
  10. {
  11. public event Action<byte[]> NotifyMsg;
  12. string PrinterName = "";
  13. string PrintType = "";
  14. PrinterList print;
  15. /// <summary>
  16. /// 拦截指定请求
  17. /// </summary>
  18. /// <param name="browserControl"></param>
  19. /// <param name="browser"></param>
  20. /// <param name="frame"></param>
  21. /// <param name="request"></param>
  22. /// <param name="response"></param>
  23. /// <returns></returns>
  24. IResponseFilter IRequestHandler.GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
  25. {
  26. MessageFilter filter;
  27. switch (request.Url.Substring(request.Url.LastIndexOf("/") + 1))
  28. {
  29. case "default?type=printer":
  30. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  31. return filter;
  32. case "zplPrint.action":
  33. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  34. return filter;
  35. case "getPrintType.action":
  36. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  37. return filter;
  38. default:
  39. break;
  40. }
  41. return null;
  42. }
  43. /// <summary>
  44. /// 完成响应后获取Js返回的数据
  45. /// </summary>
  46. /// <param name="browserControl"></param>
  47. /// <param name="browser"></param>
  48. /// <param name="frame"></param>
  49. /// <param name="request"></param>
  50. /// <param name="response"></param>
  51. /// <param name="status"></param>
  52. /// <param name="receivedContentLength"></param>
  53. void IRequestHandler.OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
  54. {
  55. MessageFilter filter;
  56. string str;
  57. Dictionary<string, object> data;
  58. switch (request.Url.Substring(request.Url.LastIndexOf("/") + 1))
  59. {
  60. case "default?type=printer":
  61. //弹出打印机选择列表
  62. print = new PrinterList(browser) { StartPosition = FormStartPosition.CenterScreen };
  63. print.Controls["Confirm"].Click += RequestHandler_Click;
  64. print.TopMost = true;
  65. print.ShowDialog();
  66. break;
  67. case "zplPrint.action":
  68. filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
  69. str = System.Text.Encoding.UTF8.GetString(filter.dataAll.ToArray());
  70. data = ToDictionary(str);
  71. //获取所有的打印格式数据
  72. string PrintCode = data["data"].ToString();
  73. List<string> PrintList = new List<string>();
  74. int PrintTime = Regex.Matches(PrintCode, "XA").Count;
  75. for (int i = 0; i < PrintTime; i++)
  76. {
  77. PrintList.Add(PrintCode.Substring(0, PrintCode.IndexOf("XZ") + 2));
  78. PrintCode = PrintCode.Substring(PrintCode.IndexOf("XZ") + 2);
  79. }
  80. for (int i = 0; i < PrintList.Count; i++)
  81. {
  82. PrintHelper.SendStringToPrinter(PrinterName, PrintList[i]);
  83. }
  84. break;
  85. case "getPrintType.action":
  86. filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
  87. str = System.Text.Encoding.UTF8.GetString(filter.dataAll.ToArray());
  88. data = ToDictionary(str);
  89. PrintType = data["data"].ToString().Replace("\"","");
  90. break;
  91. default:
  92. break;
  93. }
  94. }
  95. private void RequestHandler_Click(object sender, EventArgs e)
  96. {
  97. //设置打印机名称
  98. print.PrintDoc.PrinterSettings.PrinterName = print.Controls["Printer"].Text;
  99. PrinterName = print.Controls["Printer"].Text;
  100. //获取矩阵图的分辨率
  101. Graphics gr = print.PrintDoc.PrinterSettings.CreateMeasurementGraphics();
  102. print.browser.FocusedFrame.ExecuteJavaScriptAsync("(function(value,value1){dpi=value,printType=value1})('" + gr.DpiX + "','" + PrintType + "')");
  103. print.browser.FocusedFrame.ExecuteJavaScriptAsync("document.getElementById('confirmZplPrint').click();");
  104. print.Close();
  105. }
  106. void filter_NotifyData(byte[] data)
  107. {
  108. if (NotifyMsg != null)
  109. {
  110. NotifyMsg(data);
  111. }
  112. }
  113. public bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
  114. {
  115. return false;
  116. }
  117. public bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect)
  118. {
  119. return false;
  120. }
  121. public CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
  122. {
  123. return CefReturnValue.Continue;
  124. }
  125. public bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
  126. {
  127. return false;
  128. }
  129. public bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
  130. {
  131. return false;
  132. }
  133. public void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
  134. {
  135. }
  136. public bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
  137. {
  138. return false;
  139. }
  140. public bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
  141. {
  142. return false;
  143. }
  144. public void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
  145. {
  146. }
  147. public void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser)
  148. {
  149. }
  150. public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
  151. {
  152. }
  153. public void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, ref string newUrl)
  154. {
  155. }
  156. bool IRequestHandler.OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
  157. {
  158. return false;
  159. }
  160. public void GetData()
  161. {
  162. }
  163. public static Dictionary<string, object> ToDictionary(string JsonData)
  164. {
  165. object Data = null;
  166. Dictionary<string, object> Dic = new Dictionary<string, object>();
  167. if (JsonData.StartsWith("["))
  168. {
  169. //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
  170. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
  171. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  172. MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  173. foreach (Match ListItem in ListMatch)
  174. {
  175. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  176. }
  177. Data = List;
  178. Dic.Add("List", Data);
  179. }
  180. else
  181. {
  182. MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
  183. foreach (Match item in Match)
  184. {
  185. try
  186. {
  187. if (item.Groups[2].ToString().StartsWith("["))
  188. {
  189. //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
  190. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
  191. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  192. MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  193. foreach (Match ListItem in ListMatch)
  194. {
  195. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  196. }
  197. Data = List;
  198. }
  199. else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
  200. else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入
  201. Dic.Add(item.Groups[1].ToString(), Data);
  202. }
  203. catch { }
  204. }
  205. }
  206. return Dic;
  207. }
  208. }
  209. }