Form1.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. using System.Management;
  18. using System.Management.Instrumentation;
  19. namespace APL_Macro
  20. {
  21. public partial class Form1 : Form
  22. {
  23. private System.IO.Ports.SerialPort serialPort1;
  24. private int RowCnt = 1;
  25. // 핸들을 잡기위한 Dll Import
  26. [DllImport("user32.dll")]
  27. public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
  28. [DllImport("user32.dll")]
  29. public static extern IntPtr FindWindowEx(IntPtr hWnd1, IntPtr hWnd2, string lpsz1, string lpsz2);
  30. [DllImport("User32.Dll", EntryPoint = "PostMessageA")]
  31. public static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);
  32. [DllImport("user32.dll")]
  33. public static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);
  34. [DllImport("user32")]
  35. public static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
  36. // PostMessage 를 위한 Message Value
  37. public enum WMessages : int
  38. {
  39. WM_LBUTTONDOWN = 0x201, //Left mousebutton down
  40. WM_LBUTTONUP = 0x202, //Left mousebutton up
  41. WM_LBUTTONDBLCLK = 0x203, //Left mousebutton doubleclick
  42. WM_RBUTTONDOWN = 0x204, //Right mousebutton down
  43. WM_RBUTTONUP = 0x205, //Right mousebutton up
  44. WM_RBUTTONDBLCLK = 0x206, //Right mousebutton doubleclick
  45. WM_KEYDOWN = 0x100, //Key down
  46. WM_KEYUP = 0x101, //Key up
  47. WM_SYSKEYDOWN = 0x104,
  48. WM_SYSKEYUP = 0x105,
  49. WM_CHAR = 0x102,
  50. WM_COMMAND = 0x111
  51. }
  52. public Form1()
  53. {
  54. InitializeComponent();
  55. }
  56. protected override void WndProc(ref Message m)
  57. {
  58. UInt32 WM_DEVICECHANGE = 0x0219;
  59. //UInt32 DBT_DEVTUP_VOLUME = 0x02;
  60. UInt32 DBT_DEVTUP_VOLUME = 0x00000003;
  61. UInt32 DBT_DEVICEARRIVAL = 0x8000;
  62. UInt32 DBT_DEVICEREMOVECOMPLETE = 0x8004;
  63. if ((m.Msg == WM_DEVICECHANGE) && (m.WParam.ToInt32() == DBT_DEVICEARRIVAL))//디바이스 연결
  64. {
  65. //int m_Count = 0;
  66. int devType = Marshal.ReadInt32(m.LParam, 4);
  67. if (devType == DBT_DEVTUP_VOLUME)
  68. {
  69. SerialPort_Get();
  70. if(PrevSerialName != null){
  71. comboBox1.DataSource = PrevSerialName;
  72. Button_Start_Click(null,null);
  73. }
  74. }
  75. }
  76. if ((m.Msg == WM_DEVICECHANGE) && (m.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)) //디바이스 연결 해제
  77. {
  78. int devType = Marshal.ReadInt32(m.LParam, 4);
  79. if (devType == DBT_DEVTUP_VOLUME)
  80. {
  81. SerialPort_Get();
  82. }
  83. }
  84. base.WndProc(ref m);
  85. }
  86. string PrevSerialName;
  87. private void SerialPort_Get()
  88. {
  89. #if false
  90. ManagementObjectCollection ManObjReturn;
  91. ManagementObjectSearcher ManObjSearch;
  92. ManObjSearch = new ManagementObjectSearcher("Select * from Win32_SerialPort");
  93. ManObjReturn = ManObjSearch.Get();
  94. String[] str = new string[10];
  95. int i = 0;
  96. foreach (ManagementObject ManObj in ManObjReturn)
  97. {
  98. str[i++] = Convert.ToString(ManObj["Name"]);
  99. //comboBox1.Items.Add(Convert.ToString(ManObj["Name"]));
  100. // MessageBox.Show(Convert.ToString(ManObj["Name"]));
  101. }
  102. #endif
  103. #if false
  104. foreach (ManagementObject ManObj in ManObjReturn)
  105. {
  106. //int s = ManObj.Properties.Count;
  107. //foreach (PropertyData d in ManObj.Properties)
  108. //{
  109. // MessageBox.Show(d.Name);
  110. //}
  111. MessageBox.Show(
  112. "Device ID : " + ManObj["DeviceID"] + "\n"
  113. + "PNP Device ID : " + ManObj["PNPDeviceID"] + "\n"
  114. + "Name : " + ManObj["Name"] + "\n"
  115. + "Caption : " + ManObj["Caption"] + "\n"
  116. + "Description : " + ManObj["Description"] + "\n"
  117. + "Provider Type : " + ManObj["ProviderType"] + "\n"
  118. + "Status : " + ManObj["Status"]);
  119. }
  120. #endif
  121. #if true
  122. this.serialPort1 = new System.IO.Ports.SerialPort();
  123. this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.SP1_DataReceived);
  124. string[] port = SerialPort.GetPortNames();
  125. #endif
  126. #if true
  127. comboBox1.DataSource = null;
  128. comboBox1.BeginUpdate();
  129. foreach (string comport in SerialPort.GetPortNames())//foreach (string comport in SerialPort_TestProgram.GetPortNames())
  130. {
  131. comboBox1.Items.Add(comport);
  132. }
  133. comboBox1.EndUpdate();
  134. if(comboBox1.Enabled == true) // 연결이 안된상태
  135. comboBox1.DataSource = SerialPort.GetPortNames();
  136. else//연결된 상태 해제시 연결 해제
  137. Button_Stop_Click(null, null);
  138. #else
  139. #if false
  140. comboBox1.BeginUpdate();
  141. foreach (ManagementObject ManObj in ManObjReturn)
  142. {
  143. comboBox1.Items.Add(Convert.ToString(ManObj["Name"]));
  144. // MessageBox.Show(Convert.ToString(ManObj["Name"]));
  145. }
  146. comboBox1.EndUpdate();
  147. #else
  148. comboBox1.BeginUpdate();
  149. for(int ii = 0; ii < i; ii++)
  150. {
  151. comboBox1.Items.Add(str[ii]);
  152. // MessageBox.Show(Convert.ToString(ManObj["Name"]));
  153. }
  154. comboBox1.EndUpdate();
  155. #endif
  156. #endif
  157. if (Button_Start.Visible == false)
  158. {
  159. //comboBox1.DataSource = PrevSerialName;
  160. serialPort1.BaudRate = (int)115200;
  161. serialPort1.DataBits = (int)8;
  162. serialPort1.Parity = System.IO.Ports.Parity.None;
  163. serialPort1.StopBits = StopBits.One;
  164. serialPort1.Encoding = Encoding.UTF8;
  165. Button_Start_Click(null,null);
  166. }
  167. }
  168. private void Form1_Load(object sender, EventArgs e)
  169. {
  170. /* PrivateFontCollection privateFonts = new PrivateFontCollection();
  171. privateFonts.AddFontFile("뫼비우스 Bold.ttf");
  172. Font font = new Font(privateFonts.Families[0], 70f);*/
  173. /*label38.Font = font;
  174. label38.Text = "누액 감지 시스템";*/
  175. //SerialPort 초기 설정
  176. SerialPort_Get();
  177. comboBox1.DataSource = SerialPort.GetPortNames();
  178. serialPort1.BaudRate = (int)115200;
  179. serialPort1.DataBits = (int)8;
  180. serialPort1.Parity = System.IO.Ports.Parity.None;
  181. serialPort1.StopBits = StopBits.One;
  182. serialPort1.Encoding = Encoding.UTF8;
  183. //Serial Form _Off button 설정
  184. Button_Stop.Enabled = false; //off 기능 사라짐
  185. Button_Stop.Visible = false; //off 버튼 숨겨짐
  186. SerialFormEnagleChoice(true); //serial 설정버튼 on
  187. SetupDataGridView();
  188. }
  189. private void SetupDataGridView()
  190. {
  191. this.Controls.Add(dgvList);
  192. // DataGridView의 컬럼 갯수를 5개로 설정합니다.
  193. dgvList.ColumnCount = 2;
  194. // DataGridView에 컬럼을 추가합니다.
  195. dgvList.Columns[0].Name = "IMEI";
  196. dgvList.Columns[1].Name = "USIM";
  197. }
  198. private void SerialFormEnagleChoice(bool of)
  199. {
  200. comboBox1.Enabled = of;
  201. comboBox2.Enabled = of;
  202. }
  203. //글자 수 제한///
  204. string g_data; // 전역 변수(혹은 멤버 변수)
  205. private void SP1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  206. {
  207. //string receiveData = "";
  208. //포트로 데이터가 들어오면
  209. if (serialPort1.IsOpen)
  210. {
  211. string data = serialPort1.ReadExisting();
  212. Controller_TextLoad(data);
  213. if (Ascii_checkBox.Checked == true)
  214. {
  215. g_data += data;
  216. if (data != string.Empty)
  217. {
  218. PacketData(data);
  219. }
  220. }
  221. else
  222. {
  223. try
  224. {
  225. // 리스트 두개 사용
  226. int nLnegth = 0;
  227. nLnegth = serialPort1.BytesToRead;
  228. byte[] btTemp = new byte[nLnegth];
  229. serialPort1.Read(btTemp, 0, nLnegth);
  230. if (nLnegth > 0)
  231. {
  232. PacketData(btTemp);
  233. // 이부분에서 데이타 처리하는 부분으로 전송하여 사용하면 됨
  234. }
  235. }
  236. catch (Exception ex)
  237. {
  238. if (serialPort1.IsOpen)
  239. {
  240. System.Windows.Forms.MessageBox.Show(ex.ToString());
  241. }
  242. else
  243. {
  244. return;
  245. }
  246. }
  247. }
  248. }
  249. }
  250. /*
  251. * 데이터 수신 부분 Class to Class 전달 부분*
  252. * */
  253. private delegate void StringSend(string Text);
  254. private delegate void ValueSend(byte[] data);
  255. private delegate void BoolSend(ref CheckBox temp_Checkbox, bool data);
  256. private delegate void voidSend();
  257. private int datacnt = 0;
  258. string[] SubStr = new string[2];
  259. private void PacketData(string Text)
  260. {
  261. bool stringExists = Text.Contains("READY");
  262. if (stringExists)
  263. {
  264. // MessageBox.Show(Text);
  265. datacnt = 1;
  266. }
  267. if(datacnt >= 1)
  268. {
  269. string strTmp = Regex.Replace(Text, @"\D", "");
  270. try
  271. {
  272. if (strTmp != "")
  273. {
  274. if (strTmp.Length < 25 && datacnt == 1)
  275. {
  276. datacnt = 2;
  277. }
  278. if (datacnt == 1)
  279. {
  280. SubStr[0] = "\r\n IMEI : " + strTmp.Substring(0, Convert.ToInt32(numericUpDown_IMEI));
  281. SubStr[1] = "\r\n USIM : " + strTmp.Substring(15, Convert.ToInt32(numericUpDown_USIM));
  282. // MessageBox.Show(SubStr[0] + SubStr[1]);
  283. datacnt = 0;
  284. }
  285. else if (datacnt == 2)
  286. {
  287. SubStr[0] = "\r\n IMEI : " + strTmp.Substring(0, 15);
  288. datacnt = 3;
  289. }
  290. else if (datacnt == 3)
  291. {
  292. SubStr[1] = "\r\n USIM : " + strTmp.Substring(0, 15);
  293. // MessageBox.Show(SubStr[0] + SubStr[1]);
  294. datacnt = 0;
  295. string[] row0 = { Regex.Replace(SubStr[0], @"\D", ""), Regex.Replace(SubStr[1], @"\D", "") };
  296. // DataGridView에 한 줄씩 삽입합니다.
  297. CheckForIllegalCrossThreadCalls = false;
  298. dgvList.Rows.Add(row0);
  299. label_Cnt.Text = Convert.ToString(RowCnt++);
  300. }
  301. }
  302. }
  303. catch (Exception ex)
  304. {
  305. MessageBox.Show(ex.Message);
  306. datacnt = 1;
  307. }
  308. }
  309. System.GC.Collect(0, GCCollectionMode.Forced);
  310. System.GC.WaitForFullGCComplete();
  311. }
  312. private void PacketData(byte[] Text)
  313. {
  314. System.GC.Collect(0, GCCollectionMode.Forced);
  315. System.GC.WaitForFullGCComplete();
  316. }
  317. int LineLimit = 500;
  318. [DllImport("user32.dll")]
  319. public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
  320. private const int WM_SETREDRAW = 255;
  321. public void Controller_TextLoad(string text)
  322. {
  323. int nLimitLines = Convert.ToInt32(LineLimit); //제한 라인 수
  324. try
  325. {
  326. try
  327. {
  328. CheckForIllegalCrossThreadCalls = false;
  329. SendMessage(this.Handle, WM_SETREDRAW, false, 0);
  330. }
  331. catch(Exception ex) { MessageBox.Show(ex.Message); return; }
  332. if (richTextBox1.Lines.Length > nLimitLines)
  333. {
  334. LinkedList<string> tempLines = new LinkedList<string>(richTextBox1.Lines);
  335. while ((tempLines.Count - nLimitLines) > 0)
  336. {
  337. tempLines.RemoveFirst();
  338. }
  339. richTextBox1.Lines = tempLines.ToArray();
  340. }
  341. try
  342. {
  343. CheckForIllegalCrossThreadCalls = false;
  344. SendMessage(this.Handle, WM_SETREDRAW, true, 0);
  345. this.Refresh();
  346. }
  347. catch { return; }
  348. richTextBox1.AppendText(text);
  349. richTextBox1.SelectionStart = richTextBox1.Text.Length;//맨 마지막 선택...
  350. richTextBox1.ScrollToCaret();
  351. }
  352. catch { try { CheckForIllegalCrossThreadCalls = false; SendMessage(this.Handle, WM_SETREDRAW, true, 0); } catch { return; } }
  353. }
  354. // 이 코드에는 엑셀파일에서 불러온 데이터를 데이터그리드뷰(DataGridView)에 바인딩하는 것도 포함되어 있다.
  355. private void btnOpenExcel_Click(object sender, EventArgs e)
  356. {
  357. // 엑셀 변수 선언
  358. Excel.Application xlApp = null;
  359. Excel.Workbook xlWorkbook = null;
  360. Excel.Worksheet xlWorksheet = null;
  361. // 파일 선택
  362. OpenFileDialog ofd = new OpenFileDialog();
  363. ofd.Filter = "Excel File (*.xlsx)|*.xlsx|Excel File 97~2003 (*.xls)|*.xls|All Files (*.*)|*.*";
  364. if (ofd.ShowDialog() == DialogResult.OK)
  365. {
  366. try
  367. {
  368. // 데이터그리드뷰 클리어
  369. dgvList.Columns.Clear();
  370. // 엑셀데이터를 담을 데이터테이블 선언
  371. DataTable dt = new DataTable();
  372. // 엑셀 변수들 초기화
  373. xlApp = new Excel.Application();
  374. xlWorkbook = xlApp.Workbooks.Open(ofd.FileName);
  375. xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1); // 첫 번째 시트
  376. // 시트에서 범위 설정
  377. // UsedRange는 사용된 셀 모두이므로
  378. // 범위를 따로 지정하려면
  379. // xlWorksheet.Range[xlWorksheet.Cells[시작 행, 시작 열], xlWorksheet.Cells[끝 행, 끝 열]]
  380. Excel.Range range = xlWorksheet.UsedRange;
  381. // 2차원 배열에 담기
  382. object[,] data = range.Value;
  383. // 데이터테이블에 엑셀 칼럼만큼 칼럼 추가
  384. for (int i = 1; i <= range.Columns.Count; i++)
  385. {
  386. dt.Columns.Add(i.ToString(), typeof(string));
  387. }
  388. // 데이터테이블에 2차원 배열에 담은 엑셀데이터 추가
  389. for (int r = 1; r <= range.Rows.Count; r++)
  390. {
  391. DataRow dr = dt.Rows.Add();
  392. for (int c = 1; c <= range.Columns.Count; c++)
  393. {
  394. dr[c - 1] = data[r, c];
  395. }
  396. }
  397. xlWorkbook.Close(true);
  398. xlApp.Quit();
  399. // 데이터그리드뷰에 데이터테이블 바인딩
  400. dgvList.DataSource = dt;
  401. }
  402. catch (Exception ex)
  403. {
  404. MessageBox.Show(ex.Message);
  405. }
  406. finally
  407. {
  408. // 사용이 끝난 엑셀파일 Release
  409. ReleaseExcelObject(xlWorksheet);
  410. ReleaseExcelObject(xlWorkbook);
  411. ReleaseExcelObject(xlApp);
  412. }
  413. }
  414. }
  415. private void ReleaseExcelObject(object obj)
  416. {
  417. try
  418. {
  419. if (obj != null)
  420. {
  421. Marshal.ReleaseComObject(obj);
  422. obj = null;
  423. }
  424. }
  425. catch (Exception ex)
  426. {
  427. obj = null;
  428. throw ex;
  429. }
  430. finally
  431. {
  432. GC.Collect();
  433. }
  434. }
  435. private void Button_Start_Click(object sender, EventArgs e)
  436. {
  437. #if false
  438. int coms_index = comboBox1.Text.ToString().IndexOf("(COM");
  439. int coms_Len = comboBox1.Text.ToString().Length;
  440. string portname = comboBox1.Text.ToString().Substring(coms_index + 1, coms_Len - coms_index - 2);
  441. serialPort1.PortName = portname;//comboBox1.Text.ToString();//
  442. #else
  443. serialPort1.PortName = comboBox1.SelectedItem.ToString();
  444. int coms_index = comboBox1.Text.ToString().IndexOf("\0");
  445. PrevSerialName = comboBox1.Text;
  446. #endif
  447. //MessageBox.Show();
  448. try
  449. {
  450. serialPort1.Open();
  451. }
  452. catch (Exception ea)
  453. {
  454. MessageBox.Show(ea.Message);
  455. }
  456. if (serialPort1.IsOpen)
  457. {
  458. try
  459. {
  460. Controller_TextLoad("\nPort Open Connect!!!");
  461. }
  462. catch { }
  463. //rbText.Text = "[" + SP1.PortName.ToString() + "] Port Open Connect!!";
  464. //Serial on/off Button의 보이고 안보이게 하기
  465. Button_Start.Enabled = false; //on 기능 소멸
  466. Button_Start.Visible = false; //on 버튼 사라짐
  467. Button_Stop.Enabled = true; //off 기능 나타남
  468. Button_Stop.Visible = true; //off 버튼 나타남.
  469. SerialFormEnagleChoice(false); //serial 설정버튼 off
  470. //timer1.Start();
  471. Button_Start.Visible = false;
  472. }
  473. else
  474. {
  475. try
  476. {
  477. // Controller_Debug.tbReceived2.Text = "Port Open Failed!!!";
  478. MessageBox.Show("Port Open Failed!!! ");
  479. }
  480. catch { }
  481. }
  482. //////////////////////////다른 프로그래머의 데이터
  483. /*
  484. * if (serialPort1.IsOpen) serialPort1.Close();
  485. serialPort1.PortName = comboBox1.Text;
  486. tbReceived.Clear();
  487. tbReceived.Text += serialPort1.PortName + "Selected\n";
  488. */
  489. ////////////////////
  490. }
  491. private void Button_Stop_Click(object sender, EventArgs e)
  492. {
  493. try
  494. {
  495. serialPort1.Close();
  496. Controller_TextLoad("\nPort Closed!!! ");
  497. }
  498. catch { }
  499. // Initialize = 0;
  500. //Serial on/off Button의 보이고 안보이게 하기
  501. Button_Start.Enabled = true; //on 기능 나타남
  502. Button_Start.Visible = true; //on 버튼 나타남
  503. Button_Stop.Enabled = false; //off 기능 사라짐
  504. Button_Stop.Visible = false; //off 버튼 사라짐
  505. SerialFormEnagleChoice(true); //serial 설정버튼 on
  506. }
  507. private void Start_Clear_Click(object sender, EventArgs e)
  508. {
  509. richTextBox1.Text = "";
  510. }
  511. private void comboBox1_Click(object sender, EventArgs e)
  512. {
  513. }
  514. private void button1_Click(object sender, EventArgs e)
  515. {
  516. comboBox1.Items.Clear();
  517. SerialPort_Get();
  518. }
  519. private void comboBox1_MouseClick(object sender, MouseEventArgs e)
  520. {
  521. comboBox1.DataSource = null;
  522. comboBox1.Items.Clear();
  523. SerialPort_Get();
  524. }
  525. }
  526. }