using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using SuperWebSocket; using System.Web; using System.Web.Script.Serialization; using System.Threading; using System.IO; using System.Drawing.Imaging; using Microsoft.Win32; using System.Diagnostics; using System.Security.Principal; using ICS.model; //using AForge.Imaging.Filters; using Newtonsoft.Json; namespace ICS { public partial class Form1 : Form { private Point mouseOff; // 鼠标移动位置变量 private bool leftFlag; // 标签是否为左键 static Form1 form; static string reValue; static Dictionary<string, WebSocketSession> sessionDics = new Dictionary<string, WebSocketSession>(); public static WebSocketServer ws = null; public static log4net.ILog log = log4net.LogManager.GetLogger("ICS"); private static bool isInited = false; protected Thread threadFindWindow; private static bool isStoped = false; String eyeType = ""; public Form1() { InitializeComponent(); // 跨线程访问控件 CheckForIllegalCrossThreadCalls = false; form = this; ws = new WebSocketServer(); ws.NewSessionConnected += Ws_NewSessionConnected; ws.NewMessageReceived += Ws_NewMessageReceived; ws.SessionClosed += Ws_SessionClosed; Start(); //RegisterDll("IrisDevCtrl.ocx"); //设置开机自启动 //获取当前应用程序.exe的全路径 //string fileName = System.Reflection.Assembly.GetExecutingAssembly().Location; //SetAutoRun(fileName, true); //threadFindWindow = new Thread(FindWindow); //threadFindWindow.Start(); } public int init() { if (ConfigHelper.GetAppConfig("devType") == "1") { String light = "1A"; String strJson = "{\"white_brightness\":\"" + light + "\"}"; int result = irisColCtrl1.IrisInit(strJson); if (result == 0) { log.Info("手动初始化成功!"); return 0; } else { log.Info("手动初始化失败:" + result.ToString()); return result; } } else { string initText = "{\"log\":\"0\",\"white_brightness\":\"240\"}"; int iResult = axIrisDevCtrl1.IrisInit(initText); if (iResult == 0) { log.Info("手动初始化成功!"); return 0; } else { log.Info("手动初始化失败:" + iResult.ToString()); return -1; } } } public void Ws_NewSessionConnected(WebSocketSession session) { log.Info("与客户端:" + GetSessionName(session) + "创建新会话"); new Thread(new ThreadStart(() => { string path = AppDomain.CurrentDomain.BaseDirectory + "TEMP\\"; DeleteFolder(path); })).Start(); } private void Ws_NewMessageReceived(WebSocketSession session, string value) { log.Info("收到消息:" + value); reValue = value; try { if (!string.IsNullOrWhiteSpace(value)) { if (!sessionDics.ContainsKey(value)) sessionDics.Add(value, session); else sessionDics[value] = session; } // 开始采集 if (reValue.Contains("StartCapture")) { // 初始化采集设备 if (isInited == false) { int iResult = init(); if (iResult == 0) { isInited = true; log.Info("初始化成功!"); } else if (iResult == -109) { log.Info("初始化失败:" + iResult.ToString()); SendMsgToClient(reValue, "已经初始化!"); MessageBox.Show("已经初始化!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else if (iResult == -112) { log.Info("初始化失败:" + iResult.ToString()); SendMsgToClient(reValue, "没有搜索到采集设备!"); MessageBox.Show("没有搜索到采集设备!", "提示",MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { log.Info("初始化失败:" + iResult.ToString()); SendMsgToClient(reValue, "设备启动失败!"); MessageBox.Show("设备启动失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } if (ConfigHelper.GetAppConfig("devType") == "1") irisColCtrl1.Visible = true; else axIrisDevCtrl1.Visible = true; // 弹出界面 form.Show(); form.WindowState = FormWindowState.Normal; form.Activate(); // 开始采集 if (ConfigHelper.GetAppConfig("devType") == "1") { irisColCtrl1.Focus(); //irisColCtrl1.setUserName(textBox_name.Text); irisColCtrl1.CaptureEvent -= CaptureEvent; eyeType = "3"; if (value.Length > 2) eyeType = value.Substring(value.Length - 1); String strJson = "{\"eyeType\":\"" + eyeType + "\"}"; Thread.Sleep(100); int result = irisColCtrl1.StartCapture(strJson); log.Info("开始采集成功!"); //注册采集事件 if (result == 0) irisColCtrl1.CaptureEvent += CaptureEvent; irisColCtrl1.Capture(); } else { axIrisDevCtrl1.Focus(); string eyeType = "3"; if (value.Length > 2) eyeType = value.Substring(value.Length - 1); string collType = "{\"eyeType\":\"" + eyeType + "\"}"; irisColCtrl1.StartCapture(collType); } } // 停止采集 else if (reValue.Contains("StopCapture")) { if (ConfigHelper.GetAppConfig("devType") == "1") { irisColCtrl1.CaptureEvent -= CaptureEvent; int result = irisColCtrl1.StopCapture(); if (result == 0) { isStoped = true; this.Hide(); } //else // MessageBox.Show("停止采集失败", "提示"); } else { int re = axIrisDevCtrl1.StopCapture(); if (re == 0) { isStoped = true; this.Hide(); } } } // 关闭设备 else if (reValue.Contains("Close")) { if (ConfigHelper.GetAppConfig("devType") == "1") { irisColCtrl1.CaptureEvent -= CaptureEvent; int result = irisColCtrl1.IrisClose(); if (result == 0) { irisColCtrl1.ReSet(); irisColCtrl1.Visible = false; isInited = false; this.Hide(); } else { } //MessageBox.Show("关闭设备失败", "提示"); } else { axIrisDevCtrl1.StopCapture(); int re = axIrisDevCtrl1.IrisClose(); if (re == 0) { axIrisDevCtrl1.ReSet(); axIrisDevCtrl1.Visible = false; isInited = false; this.Hide(); } } } else if (reValue.Contains("ReadIdCard")) { string sendMsg = ""; if (ConfigHelper.GetAppConfig("cardReaderType") == "w") { sendMsg = CardReader.readCardInfo(); } else if (ConfigHelper.GetAppConfig("cardReaderType") == "b") { sendMsg = CardReader.readCardInfo2(); } if (sendMsg == "") sendMsg = "{\"message\":\"fail\"}"; SendMsgToClient(reValue, sendMsg); } } catch (Exception ex) { log.Error("Ws_NewMessageReceived 错误:" + ex.Message); } } public void Ws_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value) { log.Info("与客户端:" + GetSessionName(session) + "的会话被关闭 原因:" + value.ToString()); var msg = string.Format("{0:HH:MM:ss} {1} 离开聊天室", DateTime.Now, GetSessionName(session)); irisColCtrl1.Visible = false; SendToAll(session, msg); } /// <summary> /// 发送消息到客户端 /// </summary> /// <param name="value"></param> /// <param name="msg"></param> public static void SendMsgToClient(string value, string msg) { try { if (sessionDics.ContainsKey(value)) { var webSocketSession = sessionDics[value]; if (webSocketSession != null) { webSocketSession.Send(msg); } } } catch (Exception ex) { log.Error("SendMsgToClient 错误:" + ex.Message); } } /// <summary> /// 启动服务 /// </summary> /// <returns></returns> public static void Start() { try { int port = Convert.ToInt32(ConfigHelper.GetAppConfig("port")); if (!ws.Setup("127.0.0.1", port)) { log.Error("设置WebSocket服务侦听地址失败"); return; } if (!ws.Start()) { log.Error("启动WebSocket服务侦听失败"); return; } } catch (Exception e) { log.Error("Start exceptrion: " + e.Message); } } /// <summary> /// 停止侦听服务 /// </summary> public static void Stop() { try { if (ws != null) { ws.Stop(); } } catch (Exception e) { log.Error("Stop exceptrion: " + e.Message); } } public static string GetSessionName(WebSocketSession session) { try { return HttpUtility.UrlDecode(session.Path == null ?"":session.Path.TrimStart('/')); } catch (Exception e) { log.Error("GetSessionName 错误:" + e.Message); return ""; } } public static void SendToAll(WebSocketSession session, string msg) { foreach (var sendSession in session.AppServer.GetAllSessions()) { sendSession.Send(msg); } } private void notifyIcon1_Click(object sender, EventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; this.Activate(); irisColCtrl1.Focus(); } private void btn_hide_Click(object sender, EventArgs e) { this.Hide(); } private void panel_title_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { mouseOff = new Point(-e.X, -e.Y); //得到变量的值 leftFlag = true; //点击左键按下时标注为true; } } private void panel_title_MouseMove(object sender, MouseEventArgs e) { if (leftFlag) { Point mouseSet = Control.MousePosition; mouseSet.Offset(mouseOff.X, mouseOff.Y); //设置移动后的位置 Location = mouseSet; } } private void panel_title_MouseUp(object sender, MouseEventArgs e) { if (leftFlag) { leftFlag = false;//释放鼠标后标注为false; } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { Stop(); } /// <summary> /// 注册采集处理事件 /// </summary> /// <param name="info"></param> public void CaptureEvent(String info) { string sendMsg = ""; try { Console.WriteLine(info); ResultParam resJson = JsonConvert.DeserializeObject<ResultParam>(info); form.Hide(); irisColCtrl1.IrisClose(); irisColCtrl1.Visible = false; isInited = false; irisColCtrl1.CaptureEvent -= CaptureEvent; bool captureSuccess = true; if (eyeType == "3") { if (resJson.Hmzp_zy.Contains("左眼") || resJson.Hmzp_yy.Contains("右眼")) { captureSuccess = false; } } else if (eyeType == "2") { if (resJson.Hmzp_zy.Contains("左眼")) { captureSuccess = false; } } else if (eyeType == "1") { if (resJson.Hmzp_yy.Contains("右眼")) { captureSuccess = false; } } if (!captureSuccess) { sendMsg = "采集失败"; } else { if (eyeType == "3") { sendMsg = resJson.Hmzp_zy + ";" + resJson.Hmzp_yy + ":" + resJson.Zy_xxzlpf + ";" + resJson.Yy_xxzlpf; } else if (eyeType == "2") { sendMsg = resJson.Hmzp_zy + ":" + resJson.Zy_xxzlpf ; } else if (eyeType == "1") { sendMsg = resJson.Hmzp_yy + ":" + resJson.Yy_xxzlpf; } sendMsg = "image" + sendMsg; } } catch (Exception ex) { sendMsg = "ICS异常"; log.Error("axIrisDevCtrl1_OnCapture 错误:" + ex.Message); } finally { SendMsgToClient(reValue, sendMsg); } } private void axIrisDevCtrl1_OnCapture(object sender, AxIrisDevCtrlLib._DIrisDevCtrlEvents_OnCaptureEvent e) { string sendMsg = ""; try { new Thread(new ThreadStart(() => { form.Hide(); axIrisDevCtrl1.IrisClose(); axIrisDevCtrl1.ReSet(); axIrisDevCtrl1.Visible = false; isInited = false; })).Start(); if (e.result != 0) { if (!isStoped) sendMsg = "采集失败"; } else { string s = e.sIrisInfo; JavaScriptSerializer serializer = new JavaScriptSerializer(); Dictionary<string, object> jsonResult = (Dictionary<string, object>)serializer.DeserializeObject(e.sIrisInfo); object flgResult;//0:成功;-1:质量不合格;-2:采集超时;其他:失败; object hmzp_zy = null;//左眼虹膜图片base64编码 object hmzp_yy = null;//右眼虹膜图片base64编码 object cjtphs = null;//采集图片耗时 object sbxh = null;//设备型号 object sbbh = null;//设备编号 object zy_xxzlpf = null;//左眼图像质量评分 object yy_xxzlpf = null; //右眼图像质量评分 object sbcsdm = null; // 设备厂商代码(信用代码) jsonResult.TryGetValue("flgResult", out flgResult); jsonResult.TryGetValue("hmzp_zy", out hmzp_zy); jsonResult.TryGetValue("hmzp_yy", out hmzp_yy); jsonResult.TryGetValue("cjtphs", out cjtphs); jsonResult.TryGetValue("sbxh", out sbxh); jsonResult.TryGetValue("sbbh", out sbbh); jsonResult.TryGetValue("zy_xxzlpf", out zy_xxzlpf); jsonResult.TryGetValue("yy_xxzlpf", out yy_xxzlpf); jsonResult.TryGetValue("sbcsdm", out sbcsdm); if (flgResult.ToString() == "0") { if (hmzp_zy != null && hmzp_zy.ToString() != "") { sendMsg = hmzp_zy.ToString(); } if (hmzp_yy != null && hmzp_yy.ToString() != "") { if (sendMsg == "") sendMsg = hmzp_yy.ToString(); else sendMsg = sendMsg + ";" + hmzp_yy.ToString(); } if (eyeType == "3") { sendMsg = hmzp_zy + ";" + hmzp_yy + "+" + zy_xxzlpf + ";" + zy_xxzlpf; } else if (eyeType == "2") { sendMsg = hmzp_zy + "+" + zy_xxzlpf; } else if (eyeType == "1") { sendMsg = hmzp_yy + "+" + zy_xxzlpf; } sendMsg = "image" + sendMsg; } } } catch (Exception ex) { sendMsg = "ICS异常"; log.Error("axIrisDevCtrl1_OnCapture 错误:" + ex.Message); } finally { SendMsgToClient(reValue, sendMsg); } } private void FindWindow() { while (true) { int re = MessageBoxHelper.FindAndKillWindow("警告"); if (re == 1) { isInited = false; irisColCtrl1.Visible = false; } } } //private string toBase64deep8(string base64) //{ // string base64Deep8 = ""; // try // { // Image img = Base64StringToImage(base64); // Bitmap bitmap = (Bitmap)img; // if (img.PixelFormat == PixelFormat.Format24bppRgb) // { // Grayscale grayScaleFilter = new Grayscale(0.299, 0.587, 0.114); // bitmap = grayScaleFilter.Apply(bitmap); // } // base64Deep8 = ToBase64(bitmap); // } // catch (Exception ex) // { // log.Error("toBase64deep8 错误:" + ex.Message); // } // return base64Deep8; //} private string ToBase64(Bitmap bmp) { try { MemoryStream ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); String strbaser64 = Convert.ToBase64String(arr); return strbaser64; } catch (Exception ex) { log.Error("ImgToBase64String 转换失败 Exception:" + ex.Message); return ""; } } /// <summary> /// base64编码的文本转为图片 /// </summary> public Bitmap Base64StringToImage(string basestr) { Bitmap bitmap = null; try { String inputStr = basestr; byte[] arr = Convert.FromBase64String(inputStr); MemoryStream ms = new MemoryStream(arr); Bitmap bmp = new Bitmap(ms); bmp.Save("E:\\img\\teee.bmp"); ms.Close(); ms.Dispose(); bitmap = bmp; } catch (Exception ex) { //MessageBox.Show("Base64StringToImage 转换失败\nException:" + ex.Message); } return bitmap; } /// <summary> /// 应用程序开机自启动 /// </summary> /// <param name="fileName"></param> /// <param name="isAutoRun"></param> public static void SetAutoRun(string fileName, bool isAutoRun) { RegistryKey reg = null; //设置默认管理员运行 string admin_path = @"C:\Windows\System32\runas.exe /user:administrator /savecred "; try { if (!System.IO.File.Exists(fileName)) throw new Exception("该文件不存在!"); string name = fileName.Substring(fileName.LastIndexOf(@"\") + 1); name = name.Split('.')[0]; reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); if (reg == null) reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); object reg_obj = reg.GetValue(name); if (reg_obj != null && reg_obj.ToString().Contains(fileName)) { if (!isAutoRun) reg.SetValue(name, false); } else { if (isAutoRun) { //reg.SetValue(name, fileName); //设置需要使用默认管理员运行 reg.SetValue(name, admin_path + fileName); } else reg.SetValue(name, false); } } catch (Exception ex) { log.Error("自启动设置失败" + ex.StackTrace.ToString()); } finally { if (reg != null) reg.Close(); } } private bool RegisterDll(string fileName) { bool result = true; try { string dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);//获得要注册的dll的物理路径 if (!File.Exists(dllPath)) { log.Info("无"+fileName+"文件!"); return false; } //拼接命令参数 string startArgs = string.Format("/s \"{0}\"", dllPath); Process p = new Process();//创建一个新进程,以执行注册动作 p.StartInfo.FileName = "regsvr32"; p.StartInfo.Arguments = startArgs; //以管理员权限注册dll文件 WindowsIdentity winIdentity = WindowsIdentity.GetCurrent(); //引用命名空间 System.Security.Principal WindowsPrincipal winPrincipal = new WindowsPrincipal(winIdentity); if (!winPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) { p.StartInfo.Verb = "runas";//管理员权限运行 } p.Start(); p.WaitForExit(); p.Close(); p.Dispose(); } catch (Exception ex) { log.Error("RegisterDll 错误:" + ex.Message); result = false; //记录日志,抛出异常 } return result; } /// <summary> /// 删除文件夹及其内容 /// </summary> /// <param name="dir"></param> public void DeleteFolder(string dir) { foreach (string d in Directory.GetFileSystemEntries(dir)) { if (File.Exists(d)) { FileInfo fi = new FileInfo(d); if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1) fi.Attributes = FileAttributes.Normal; File.Delete(d);//直接删除其中的文件 } else DeleteFolder(d);////递归删除子文件夹 //Directory.Delete(d); } } private void axIrisDevCtrl1_PaddingChanged(object sender, EventArgs e) { } private void irisColCtrl1_CaptureEvent(string info) { } private void label_initDev_Click(object sender, EventArgs e) { label_initDev.Visible = false; if (ConfigHelper.GetAppConfig("devType") == "1") irisColCtrl1.IrisClose(); else axIrisDevCtrl1.IrisClose(); if (init() == 0) { int iRet = -1; ; int iPort = 1001; iRet = CardReader.SDT_OpenPort(iPort); if (iRet != 0x90) { CardReader.cardReaderInited = false; CardReader.cardReaderInited2 = false; MessageBox.Show("身份证读卡器初始化失败!", "提示"); CardReader.SDT_ClosePort(iPort); } else { CardReader.cardReaderInited = true; CardReader.cardReaderInited2 = true; MessageBox.Show("设备初始化成功!"); } } else { MessageBox.Show("采集设备初始化失败!"); } } private void button1_Click(object sender, EventArgs e) { label_initDev.Visible = true; } } }