Form1.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. using Excel = Microsoft.Office.Interop.Excel;
  12. using System.Data.OleDb;
  13. //Add
  14. using System.IO;
  15. using System.IO.Ports;
  16. using System.Text.RegularExpressions;
  17. namespace APL_Macro
  18. {
  19. public partial class Form1 : Form
  20. {
  21. private System.IO.Ports.SerialPort serialPort1;
  22. // 핸들을 잡기위한 Dll Import
  23. [DllImport("user32.dll")]
  24. public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
  25. [DllImport("user32.dll")]
  26. public static extern IntPtr FindWindowEx(IntPtr hWnd1, IntPtr hWnd2, string lpsz1, string lpsz2);
  27. [DllImport("User32.Dll", EntryPoint = "PostMessageA")]
  28. public static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);
  29. [DllImport("user32.dll")]
  30. public static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);
  31. [DllImport("user32")]
  32. public static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
  33. // PostMessage 를 위한 Message Value
  34. public enum WMessages : int
  35. {
  36. WM_LBUTTONDOWN = 0x201, //Left mousebutton down
  37. WM_LBUTTONUP = 0x202, //Left mousebutton up
  38. WM_LBUTTONDBLCLK = 0x203, //Left mousebutton doubleclick
  39. WM_RBUTTONDOWN = 0x204, //Right mousebutton down
  40. WM_RBUTTONUP = 0x205, //Right mousebutton up
  41. WM_RBUTTONDBLCLK = 0x206, //Right mousebutton doubleclick
  42. WM_KEYDOWN = 0x100, //Key down
  43. WM_KEYUP = 0x101, //Key up
  44. WM_SYSKEYDOWN = 0x104,
  45. WM_SYSKEYUP = 0x105,
  46. WM_CHAR = 0x102,
  47. WM_COMMAND = 0x111
  48. }
  49. public Form1()
  50. {
  51. InitializeComponent();
  52. }
  53. private void Form1_Load(object sender, EventArgs e)
  54. {
  55. /* PrivateFontCollection privateFonts = new PrivateFontCollection();
  56. privateFonts.AddFontFile("뫼비우스 Bold.ttf");
  57. Font font = new Font(privateFonts.Families[0], 70f);*/
  58. /*label38.Font = font;
  59. label38.Text = "누액 감지 시스템";*/
  60. this.serialPort1 = new System.IO.Ports.SerialPort();
  61. this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.SP1_DataReceived);
  62. comboBox1.BeginUpdate();
  63. foreach (string comport in SerialPort.GetPortNames())//foreach (string comport in SerialPort_TestProgram.GetPortNames())
  64. {
  65. comboBox1.Items.Add(comport);
  66. }
  67. comboBox1.EndUpdate();
  68. //SerialPort 초기 설정
  69. comboBox1.DataSource = SerialPort.GetPortNames();
  70. serialPort1.BaudRate = (int)115200;
  71. serialPort1.DataBits = (int)8;
  72. serialPort1.Parity = System.IO.Ports.Parity.None;
  73. serialPort1.StopBits = StopBits.One;
  74. //Serial Form _Off button 설정
  75. Button_Stop.Enabled = false; //off 기능 사라짐
  76. Button_Stop.Visible = false; //off 버튼 숨겨짐
  77. SerialFormEnagleChoice(true); //serial 설정버튼 on
  78. SetupDataGridView();
  79. }
  80. private void SetupDataGridView()
  81. {
  82. this.Controls.Add(dgvList);
  83. // DataGridView의 컬럼 갯수를 5개로 설정합니다.
  84. dgvList.ColumnCount = 2;
  85. // DataGridView에 컬럼을 추가합니다.
  86. dgvList.Columns[0].Name = "IMEI";
  87. dgvList.Columns[1].Name = "USIM";
  88. }
  89. private void SerialFormEnagleChoice(bool of)
  90. {
  91. comboBox1.Enabled = of;
  92. comboBox2.Enabled = of;
  93. }
  94. //글자 수 제한///
  95. string g_data; // 전역 변수(혹은 멤버 변수)
  96. private void SP1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  97. {
  98. //string receiveData = "";
  99. //포트로 데이터가 들어오면
  100. if (serialPort1.IsOpen)
  101. {
  102. if (Ascii_checkBox.Checked == true)
  103. {
  104. string data = serialPort1.ReadExisting();
  105. g_data += data;
  106. if (data != string.Empty)
  107. {
  108. Controller_TextLoad(data);
  109. PacketData(data);
  110. }
  111. }
  112. else
  113. {
  114. try
  115. {
  116. // 리스트 두개 사용
  117. int nLnegth = 0;
  118. nLnegth = serialPort1.BytesToRead;
  119. byte[] btTemp = new byte[nLnegth];
  120. serialPort1.Read(btTemp, 0, nLnegth);
  121. if (nLnegth > 0)
  122. {
  123. PacketData(btTemp);
  124. // 이부분에서 데이타 처리하는 부분으로 전송하여 사용하면 됨
  125. }
  126. }
  127. catch (Exception ex)
  128. {
  129. if (serialPort1.IsOpen)
  130. {
  131. System.Windows.Forms.MessageBox.Show(ex.ToString());
  132. }
  133. else
  134. {
  135. return;
  136. }
  137. }
  138. }
  139. }
  140. }
  141. /*
  142. * 데이터 수신 부분 Class to Class 전달 부분*
  143. * */
  144. private delegate void StringSend(string Text);
  145. private delegate void ValueSend(byte[] data);
  146. private delegate void BoolSend(ref CheckBox temp_Checkbox, bool data);
  147. private delegate void voidSend();
  148. private int datacnt = 0;
  149. string[] SubStr = new string[2];
  150. private void PacketData(string Text)
  151. {
  152. bool stringExists = Text.Contains("READY");
  153. if (stringExists)
  154. {
  155. MessageBox.Show(Text);
  156. datacnt = 1;
  157. }
  158. if(datacnt >= 1)
  159. {
  160. string strTmp = Regex.Replace(Text, @"\D", "");
  161. try
  162. {
  163. if (strTmp != "")
  164. {
  165. if (strTmp.Length < 25 && datacnt == 1)
  166. {
  167. datacnt = 2;
  168. }
  169. if (datacnt == 1)
  170. {
  171. SubStr[0] = "\r\n IMEI : " + strTmp.Substring(0, 15);
  172. SubStr[1] = "\r\n USIM : " + strTmp.Substring(15, 15);
  173. MessageBox.Show(SubStr[0] + SubStr[1]);
  174. datacnt = 0;
  175. }
  176. else if (datacnt == 2)
  177. {
  178. SubStr[0] = "\r\n IMEI : " + strTmp.Substring(0, 15);
  179. datacnt = 3;
  180. }
  181. else if (datacnt == 3)
  182. {
  183. SubStr[1] = "\r\n USIM : " + strTmp.Substring(0, 15);
  184. MessageBox.Show(SubStr[0] + SubStr[1]);
  185. datacnt = 0;
  186. string[] row0 = { Regex.Replace(SubStr[0], @"\D", ""), Regex.Replace(SubStr[1], @"\D", "") };
  187. // DataGridView에 한 줄씩 삽입합니다.
  188. CheckForIllegalCrossThreadCalls = false;
  189. dgvList.Rows.Add(row0);
  190. }
  191. }
  192. }
  193. catch (Exception ex)
  194. {
  195. MessageBox.Show(ex.Message);
  196. datacnt = 1;
  197. }
  198. }
  199. System.GC.Collect(0, GCCollectionMode.Forced);
  200. System.GC.WaitForFullGCComplete();
  201. }
  202. private void PacketData(byte[] Text)
  203. {
  204. System.GC.Collect(0, GCCollectionMode.Forced);
  205. System.GC.WaitForFullGCComplete();
  206. }
  207. int LineLimit = 500;
  208. [DllImport("user32.dll")]
  209. public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
  210. private const int WM_SETREDRAW = 255;
  211. public void Controller_TextLoad(string text)
  212. {
  213. int nLimitLines = Convert.ToInt32(LineLimit); //제한 라인 수
  214. try
  215. {
  216. try
  217. {
  218. SendMessage(this.Handle, WM_SETREDRAW, false, 0);
  219. }
  220. catch { return; }
  221. if (richTextBox1.Lines.Length > nLimitLines)
  222. {
  223. LinkedList<string> tempLines = new LinkedList<string>(richTextBox1.Lines);
  224. while ((tempLines.Count - nLimitLines) > 0)
  225. {
  226. tempLines.RemoveFirst();
  227. }
  228. richTextBox1.Lines = tempLines.ToArray();
  229. }
  230. try
  231. {
  232. SendMessage(this.Handle, WM_SETREDRAW, true, 0);
  233. }
  234. catch { return; }
  235. richTextBox1.AppendText(text);
  236. richTextBox1.SelectionStart = richTextBox1.Text.Length;//맨 마지막 선택...
  237. richTextBox1.ScrollToCaret();
  238. }
  239. catch { try { SendMessage(this.Handle, WM_SETREDRAW, true, 0); } catch { return; } }
  240. }
  241. // 이 코드에는 엑셀파일에서 불러온 데이터를 데이터그리드뷰(DataGridView)에 바인딩하는 것도 포함되어 있다.
  242. private void btnOpenExcel_Click(object sender, EventArgs e)
  243. {
  244. // 엑셀 변수 선언
  245. Excel.Application xlApp = null;
  246. Excel.Workbook xlWorkbook = null;
  247. Excel.Worksheet xlWorksheet = null;
  248. // 파일 선택
  249. OpenFileDialog ofd = new OpenFileDialog();
  250. ofd.Filter = "Excel File (*.xlsx)|*.xlsx|Excel File 97~2003 (*.xls)|*.xls|All Files (*.*)|*.*";
  251. if (ofd.ShowDialog() == DialogResult.OK)
  252. {
  253. try
  254. {
  255. // 데이터그리드뷰 클리어
  256. dgvList.Columns.Clear();
  257. // 엑셀데이터를 담을 데이터테이블 선언
  258. DataTable dt = new DataTable();
  259. // 엑셀 변수들 초기화
  260. xlApp = new Excel.Application();
  261. xlWorkbook = xlApp.Workbooks.Open(ofd.FileName);
  262. xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1); // 첫 번째 시트
  263. // 시트에서 범위 설정
  264. // UsedRange는 사용된 셀 모두이므로
  265. // 범위를 따로 지정하려면
  266. // xlWorksheet.Range[xlWorksheet.Cells[시작 행, 시작 열], xlWorksheet.Cells[끝 행, 끝 열]]
  267. Excel.Range range = xlWorksheet.UsedRange;
  268. // 2차원 배열에 담기
  269. object[,] data = range.Value;
  270. // 데이터테이블에 엑셀 칼럼만큼 칼럼 추가
  271. for (int i = 1; i <= range.Columns.Count; i++)
  272. {
  273. dt.Columns.Add(i.ToString(), typeof(string));
  274. }
  275. // 데이터테이블에 2차원 배열에 담은 엑셀데이터 추가
  276. for (int r = 1; r <= range.Rows.Count; r++)
  277. {
  278. DataRow dr = dt.Rows.Add();
  279. for (int c = 1; c <= range.Columns.Count; c++)
  280. {
  281. dr[c - 1] = data[r, c];
  282. }
  283. }
  284. xlWorkbook.Close(true);
  285. xlApp.Quit();
  286. // 데이터그리드뷰에 데이터테이블 바인딩
  287. dgvList.DataSource = dt;
  288. }
  289. catch (Exception ex)
  290. {
  291. MessageBox.Show(ex.Message);
  292. }
  293. finally
  294. {
  295. // 사용이 끝난 엑셀파일 Release
  296. ReleaseExcelObject(xlWorksheet);
  297. ReleaseExcelObject(xlWorkbook);
  298. ReleaseExcelObject(xlApp);
  299. }
  300. }
  301. }
  302. private void ReleaseExcelObject(object obj)
  303. {
  304. try
  305. {
  306. if (obj != null)
  307. {
  308. Marshal.ReleaseComObject(obj);
  309. obj = null;
  310. }
  311. }
  312. catch (Exception ex)
  313. {
  314. obj = null;
  315. throw ex;
  316. }
  317. finally
  318. {
  319. GC.Collect();
  320. }
  321. }
  322. private void Button_Start_Click(object sender, EventArgs e)
  323. {
  324. serialPort1.PortName = comboBox1.SelectedItem.ToString();
  325. serialPort1.PortName = comboBox1.Text.ToString();//
  326. try
  327. {
  328. serialPort1.Open();
  329. }
  330. catch (Exception ea)
  331. {
  332. MessageBox.Show(ea.Message);
  333. }
  334. if (serialPort1.IsOpen)
  335. {
  336. try
  337. {
  338. PacketData("Port Open Connect!!!\r\n");
  339. }
  340. catch { }
  341. //rbText.Text = "[" + SP1.PortName.ToString() + "] Port Open Connect!!";
  342. //Serial on/off Button의 보이고 안보이게 하기
  343. Button_Start.Enabled = false; //on 기능 소멸
  344. Button_Start.Visible = false; //on 버튼 사라짐
  345. Button_Stop.Enabled = true; //off 기능 나타남
  346. Button_Stop.Visible = true; //off 버튼 나타남.
  347. SerialFormEnagleChoice(false); //serial 설정버튼 off
  348. //timer1.Start();
  349. Button_Start.Visible = false;
  350. }
  351. else
  352. {
  353. try
  354. {
  355. // Controller_Debug.tbReceived2.Text = "Port Open Failed!!!";
  356. MessageBox.Show("Port Open Failed!!!");
  357. }
  358. catch { }
  359. }
  360. //////////////////////////다른 프로그래머의 데이터
  361. /*
  362. * if (serialPort1.IsOpen) serialPort1.Close();
  363. serialPort1.PortName = comboBox1.Text;
  364. tbReceived.Clear();
  365. tbReceived.Text += serialPort1.PortName + "Selected\n";
  366. */
  367. ////////////////////
  368. }
  369. }
  370. }