123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using Excel = Microsoft.Office.Interop.Excel;
- using System.Data.OleDb;
- //Add
- using System.IO;
- using System.IO.Ports;
- using System.Text.RegularExpressions;
- namespace APL_Macro
- {
- public partial class Form1 : Form
- {
- private System.IO.Ports.SerialPort serialPort1;
-
- // 핸들을 잡기위한 Dll Import
- [DllImport("user32.dll")]
- public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
- [DllImport("user32.dll")]
- public static extern IntPtr FindWindowEx(IntPtr hWnd1, IntPtr hWnd2, string lpsz1, string lpsz2);
- [DllImport("User32.Dll", EntryPoint = "PostMessageA")]
- public static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);
- [DllImport("user32.dll")]
- public static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);
- [DllImport("user32")]
- public static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
-
- // PostMessage 를 위한 Message Value
- public enum WMessages : int
- {
- WM_LBUTTONDOWN = 0x201, //Left mousebutton down
- WM_LBUTTONUP = 0x202, //Left mousebutton up
- WM_LBUTTONDBLCLK = 0x203, //Left mousebutton doubleclick
- WM_RBUTTONDOWN = 0x204, //Right mousebutton down
- WM_RBUTTONUP = 0x205, //Right mousebutton up
- WM_RBUTTONDBLCLK = 0x206, //Right mousebutton doubleclick
- WM_KEYDOWN = 0x100, //Key down
- WM_KEYUP = 0x101, //Key up
- WM_SYSKEYDOWN = 0x104,
- WM_SYSKEYUP = 0x105,
- WM_CHAR = 0x102,
- WM_COMMAND = 0x111
- }
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- /* PrivateFontCollection privateFonts = new PrivateFontCollection();
- privateFonts.AddFontFile("뫼비우스 Bold.ttf");
- Font font = new Font(privateFonts.Families[0], 70f);*/
- /*label38.Font = font;
- label38.Text = "누액 감지 시스템";*/
- this.serialPort1 = new System.IO.Ports.SerialPort();
- this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.SP1_DataReceived);
- comboBox1.BeginUpdate();
- foreach (string comport in SerialPort.GetPortNames())//foreach (string comport in SerialPort_TestProgram.GetPortNames())
- {
- comboBox1.Items.Add(comport);
- }
- comboBox1.EndUpdate();
- //SerialPort 초기 설정
- comboBox1.DataSource = SerialPort.GetPortNames();
- serialPort1.BaudRate = (int)115200;
- serialPort1.DataBits = (int)8;
- serialPort1.Parity = System.IO.Ports.Parity.None;
- serialPort1.StopBits = StopBits.One;
- //Serial Form _Off button 설정
- Button_Stop.Enabled = false; //off 기능 사라짐
- Button_Stop.Visible = false; //off 버튼 숨겨짐
- SerialFormEnagleChoice(true); //serial 설정버튼 on
- SetupDataGridView();
- }
- private void SetupDataGridView()
- {
- this.Controls.Add(dgvList);
- // DataGridView의 컬럼 갯수를 5개로 설정합니다.
- dgvList.ColumnCount = 2;
- // DataGridView에 컬럼을 추가합니다.
- dgvList.Columns[0].Name = "IMEI";
- dgvList.Columns[1].Name = "USIM";
- }
- private void SerialFormEnagleChoice(bool of)
- {
- comboBox1.Enabled = of;
- comboBox2.Enabled = of;
- }
- //글자 수 제한///
- string g_data; // 전역 변수(혹은 멤버 변수)
- private void SP1_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- //string receiveData = "";
- //포트로 데이터가 들어오면
- if (serialPort1.IsOpen)
- {
- if (Ascii_checkBox.Checked == true)
- {
- string data = serialPort1.ReadExisting();
- g_data += data;
- if (data != string.Empty)
- {
- Controller_TextLoad(data);
- PacketData(data);
- }
- }
- else
- {
- try
- {
- // 리스트 두개 사용
- int nLnegth = 0;
- nLnegth = serialPort1.BytesToRead;
- byte[] btTemp = new byte[nLnegth];
- serialPort1.Read(btTemp, 0, nLnegth);
- if (nLnegth > 0)
- {
- PacketData(btTemp);
- // 이부분에서 데이타 처리하는 부분으로 전송하여 사용하면 됨
- }
- }
- catch (Exception ex)
- {
- if (serialPort1.IsOpen)
- {
- System.Windows.Forms.MessageBox.Show(ex.ToString());
- }
- else
- {
- return;
- }
- }
- }
- }
- }
- /*
- * 데이터 수신 부분 Class to Class 전달 부분*
- * */
- private delegate void StringSend(string Text);
- private delegate void ValueSend(byte[] data);
- private delegate void BoolSend(ref CheckBox temp_Checkbox, bool data);
- private delegate void voidSend();
- private int datacnt = 0;
- string[] SubStr = new string[2];
- private void PacketData(string Text)
- {
-
- bool stringExists = Text.Contains("READY");
- if (stringExists)
- {
- MessageBox.Show(Text);
- datacnt = 1;
- }
- if(datacnt >= 1)
- {
- string strTmp = Regex.Replace(Text, @"\D", "");
- try
- {
- if (strTmp != "")
- {
- if (strTmp.Length < 25 && datacnt == 1)
- {
- datacnt = 2;
- }
- if (datacnt == 1)
- {
- SubStr[0] = "\r\n IMEI : " + strTmp.Substring(0, 15);
- SubStr[1] = "\r\n USIM : " + strTmp.Substring(15, 15);
- MessageBox.Show(SubStr[0] + SubStr[1]);
- datacnt = 0;
- }
- else if (datacnt == 2)
- {
- SubStr[0] = "\r\n IMEI : " + strTmp.Substring(0, 15);
- datacnt = 3;
- }
- else if (datacnt == 3)
- {
- SubStr[1] = "\r\n USIM : " + strTmp.Substring(0, 15);
- MessageBox.Show(SubStr[0] + SubStr[1]);
- datacnt = 0;
- string[] row0 = { Regex.Replace(SubStr[0], @"\D", ""), Regex.Replace(SubStr[1], @"\D", "") };
- // DataGridView에 한 줄씩 삽입합니다.
- CheckForIllegalCrossThreadCalls = false;
- dgvList.Rows.Add(row0);
- }
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- datacnt = 1;
- }
-
- }
- System.GC.Collect(0, GCCollectionMode.Forced);
- System.GC.WaitForFullGCComplete();
- }
- private void PacketData(byte[] Text)
- {
-
- System.GC.Collect(0, GCCollectionMode.Forced);
- System.GC.WaitForFullGCComplete();
- }
- int LineLimit = 500;
- [DllImport("user32.dll")]
- public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
- private const int WM_SETREDRAW = 255;
- public void Controller_TextLoad(string text)
- {
- int nLimitLines = Convert.ToInt32(LineLimit); //제한 라인 수
- try
- {
- try
- {
- SendMessage(this.Handle, WM_SETREDRAW, false, 0);
- }
- catch { return; }
- if (richTextBox1.Lines.Length > nLimitLines)
- {
- LinkedList<string> tempLines = new LinkedList<string>(richTextBox1.Lines);
- while ((tempLines.Count - nLimitLines) > 0)
- {
- tempLines.RemoveFirst();
- }
- richTextBox1.Lines = tempLines.ToArray();
- }
- try
- {
- SendMessage(this.Handle, WM_SETREDRAW, true, 0);
- }
- catch { return; }
- richTextBox1.AppendText(text);
- richTextBox1.SelectionStart = richTextBox1.Text.Length;//맨 마지막 선택...
- richTextBox1.ScrollToCaret();
- }
- catch { try { SendMessage(this.Handle, WM_SETREDRAW, true, 0); } catch { return; } }
- }
- // 이 코드에는 엑셀파일에서 불러온 데이터를 데이터그리드뷰(DataGridView)에 바인딩하는 것도 포함되어 있다.
- private void btnOpenExcel_Click(object sender, EventArgs e)
- {
- // 엑셀 변수 선언
- Excel.Application xlApp = null;
- Excel.Workbook xlWorkbook = null;
- Excel.Worksheet xlWorksheet = null;
- // 파일 선택
- OpenFileDialog ofd = new OpenFileDialog();
- ofd.Filter = "Excel File (*.xlsx)|*.xlsx|Excel File 97~2003 (*.xls)|*.xls|All Files (*.*)|*.*";
- if (ofd.ShowDialog() == DialogResult.OK)
- {
- try
- {
- // 데이터그리드뷰 클리어
- dgvList.Columns.Clear();
- // 엑셀데이터를 담을 데이터테이블 선언
- DataTable dt = new DataTable();
- // 엑셀 변수들 초기화
- xlApp = new Excel.Application();
- xlWorkbook = xlApp.Workbooks.Open(ofd.FileName);
- xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1); // 첫 번째 시트
- // 시트에서 범위 설정
- // UsedRange는 사용된 셀 모두이므로
- // 범위를 따로 지정하려면
- // xlWorksheet.Range[xlWorksheet.Cells[시작 행, 시작 열], xlWorksheet.Cells[끝 행, 끝 열]]
- Excel.Range range = xlWorksheet.UsedRange;
- // 2차원 배열에 담기
- object[,] data = range.Value;
- // 데이터테이블에 엑셀 칼럼만큼 칼럼 추가
- for (int i = 1; i <= range.Columns.Count; i++)
- {
- dt.Columns.Add(i.ToString(), typeof(string));
- }
- // 데이터테이블에 2차원 배열에 담은 엑셀데이터 추가
- for (int r = 1; r <= range.Rows.Count; r++)
- {
- DataRow dr = dt.Rows.Add();
- for (int c = 1; c <= range.Columns.Count; c++)
- {
- dr[c - 1] = data[r, c];
- }
- }
- xlWorkbook.Close(true);
- xlApp.Quit();
- // 데이터그리드뷰에 데이터테이블 바인딩
- dgvList.DataSource = dt;
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- finally
- {
- // 사용이 끝난 엑셀파일 Release
- ReleaseExcelObject(xlWorksheet);
- ReleaseExcelObject(xlWorkbook);
- ReleaseExcelObject(xlApp);
- }
- }
- }
- private void ReleaseExcelObject(object obj)
- {
- try
- {
- if (obj != null)
- {
- Marshal.ReleaseComObject(obj);
- obj = null;
- }
- }
- catch (Exception ex)
- {
- obj = null;
- throw ex;
- }
- finally
- {
- GC.Collect();
- }
- }
- private void Button_Start_Click(object sender, EventArgs e)
- {
- serialPort1.PortName = comboBox1.SelectedItem.ToString();
- serialPort1.PortName = comboBox1.Text.ToString();//
- try
- {
- serialPort1.Open();
- }
- catch (Exception ea)
- {
- MessageBox.Show(ea.Message);
- }
- if (serialPort1.IsOpen)
- {
- try
- {
- PacketData("Port Open Connect!!!\r\n");
- }
- catch { }
- //rbText.Text = "[" + SP1.PortName.ToString() + "] Port Open Connect!!";
- //Serial on/off Button의 보이고 안보이게 하기
- Button_Start.Enabled = false; //on 기능 소멸
- Button_Start.Visible = false; //on 버튼 사라짐
- Button_Stop.Enabled = true; //off 기능 나타남
- Button_Stop.Visible = true; //off 버튼 나타남.
- SerialFormEnagleChoice(false); //serial 설정버튼 off
- //timer1.Start();
- Button_Start.Visible = false;
- }
- else
- {
- try
- {
- // Controller_Debug.tbReceived2.Text = "Port Open Failed!!!";
- MessageBox.Show("Port Open Failed!!!");
- }
- catch { }
- }
- //////////////////////////다른 프로그래머의 데이터
- /*
- * if (serialPort1.IsOpen) serialPort1.Close();
- serialPort1.PortName = comboBox1.Text;
- tbReceived.Clear();
- tbReceived.Text += serialPort1.PortName + "Selected\n";
- */
- ////////////////////
- }
- }
- }
|