123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600 |
- 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;
- using System.Management;
- using System.Management.Instrumentation;
- namespace APL_Macro
- {
- public partial class Form1 : Form
- {
- private System.IO.Ports.SerialPort serialPort1;
- private int RowCnt = 1;
- // 핸들을 잡기위한 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();
- }
- protected override void WndProc(ref Message m)
- {
- UInt32 WM_DEVICECHANGE = 0x0219;
- //UInt32 DBT_DEVTUP_VOLUME = 0x02;
- UInt32 DBT_DEVTUP_VOLUME = 0x00000003;
-
- UInt32 DBT_DEVICEARRIVAL = 0x8000;
- UInt32 DBT_DEVICEREMOVECOMPLETE = 0x8004;
- if ((m.Msg == WM_DEVICECHANGE) && (m.WParam.ToInt32() == DBT_DEVICEARRIVAL))//디바이스 연결
- {
- //int m_Count = 0;
- int devType = Marshal.ReadInt32(m.LParam, 4);
- if (devType == DBT_DEVTUP_VOLUME)
- {
- SerialPort_Get();
- if(PrevSerialName != null){
- comboBox1.DataSource = PrevSerialName;
- Button_Start_Click(null,null);
- }
- }
- }
- if ((m.Msg == WM_DEVICECHANGE) && (m.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)) //디바이스 연결 해제
- {
- int devType = Marshal.ReadInt32(m.LParam, 4);
- if (devType == DBT_DEVTUP_VOLUME)
- {
-
- SerialPort_Get();
- }
- }
- base.WndProc(ref m);
- }
- string PrevSerialName;
- private void SerialPort_Get()
- {
- #if false
- ManagementObjectCollection ManObjReturn;
- ManagementObjectSearcher ManObjSearch;
- ManObjSearch = new ManagementObjectSearcher("Select * from Win32_SerialPort");
- ManObjReturn = ManObjSearch.Get();
- String[] str = new string[10];
- int i = 0;
- foreach (ManagementObject ManObj in ManObjReturn)
- {
- str[i++] = Convert.ToString(ManObj["Name"]);
- //comboBox1.Items.Add(Convert.ToString(ManObj["Name"]));
- // MessageBox.Show(Convert.ToString(ManObj["Name"]));
- }
- #endif
- #if false
- foreach (ManagementObject ManObj in ManObjReturn)
- {
- //int s = ManObj.Properties.Count;
- //foreach (PropertyData d in ManObj.Properties)
- //{
- // MessageBox.Show(d.Name);
- //}
- MessageBox.Show(
- "Device ID : " + ManObj["DeviceID"] + "\n"
- + "PNP Device ID : " + ManObj["PNPDeviceID"] + "\n"
- + "Name : " + ManObj["Name"] + "\n"
- + "Caption : " + ManObj["Caption"] + "\n"
- + "Description : " + ManObj["Description"] + "\n"
- + "Provider Type : " + ManObj["ProviderType"] + "\n"
- + "Status : " + ManObj["Status"]);
- }
- #endif
- #if true
- this.serialPort1 = new System.IO.Ports.SerialPort();
- this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.SP1_DataReceived);
- string[] port = SerialPort.GetPortNames();
- #endif
- #if true
- comboBox1.DataSource = null;
- comboBox1.BeginUpdate();
- foreach (string comport in SerialPort.GetPortNames())//foreach (string comport in SerialPort_TestProgram.GetPortNames())
- {
- comboBox1.Items.Add(comport);
- }
- comboBox1.EndUpdate();
- if(comboBox1.Enabled == true) // 연결이 안된상태
- comboBox1.DataSource = SerialPort.GetPortNames();
- else//연결된 상태 해제시 연결 해제
- Button_Stop_Click(null, null);
- #else
- #if false
- comboBox1.BeginUpdate();
- foreach (ManagementObject ManObj in ManObjReturn)
- {
- comboBox1.Items.Add(Convert.ToString(ManObj["Name"]));
- // MessageBox.Show(Convert.ToString(ManObj["Name"]));
- }
- comboBox1.EndUpdate();
- #else
- comboBox1.BeginUpdate();
- for(int ii = 0; ii < i; ii++)
- {
- comboBox1.Items.Add(str[ii]);
- // MessageBox.Show(Convert.ToString(ManObj["Name"]));
- }
- comboBox1.EndUpdate();
- #endif
- #endif
- if (Button_Start.Visible == false)
- {
- //comboBox1.DataSource = PrevSerialName;
- serialPort1.BaudRate = (int)115200;
- serialPort1.DataBits = (int)8;
- serialPort1.Parity = System.IO.Ports.Parity.None;
- serialPort1.StopBits = StopBits.One;
- serialPort1.Encoding = Encoding.UTF8;
- Button_Start_Click(null,null);
- }
- }
- 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 = "누액 감지 시스템";*/
-
- //SerialPort 초기 설정
- SerialPort_Get();
- comboBox1.DataSource = SerialPort.GetPortNames();
- serialPort1.BaudRate = (int)115200;
- serialPort1.DataBits = (int)8;
- serialPort1.Parity = System.IO.Ports.Parity.None;
- serialPort1.StopBits = StopBits.One;
- serialPort1.Encoding = Encoding.UTF8;
- //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)
- {
- string data = serialPort1.ReadExisting();
- Controller_TextLoad(data);
- if (Ascii_checkBox.Checked == true)
- {
-
- g_data += data;
- if (data != string.Empty)
- {
- 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, Convert.ToInt32(numericUpDown_IMEI));
- SubStr[1] = "\r\n USIM : " + strTmp.Substring(15, Convert.ToInt32(numericUpDown_USIM));
-
- // 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);
- label_Cnt.Text = Convert.ToString(RowCnt++);
- }
- }
- }
- 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
- {
- CheckForIllegalCrossThreadCalls = false;
- SendMessage(this.Handle, WM_SETREDRAW, false, 0);
- }
- catch(Exception ex) { MessageBox.Show(ex.Message); 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
- {
- CheckForIllegalCrossThreadCalls = false;
- SendMessage(this.Handle, WM_SETREDRAW, true, 0);
- this.Refresh();
- }
- catch { return; }
- richTextBox1.AppendText(text);
- richTextBox1.SelectionStart = richTextBox1.Text.Length;//맨 마지막 선택...
- richTextBox1.ScrollToCaret();
- }
- catch { try { CheckForIllegalCrossThreadCalls = false; 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)
- {
- #if false
- int coms_index = comboBox1.Text.ToString().IndexOf("(COM");
- int coms_Len = comboBox1.Text.ToString().Length;
- string portname = comboBox1.Text.ToString().Substring(coms_index + 1, coms_Len - coms_index - 2);
- serialPort1.PortName = portname;//comboBox1.Text.ToString();//
- #else
- serialPort1.PortName = comboBox1.SelectedItem.ToString();
- int coms_index = comboBox1.Text.ToString().IndexOf("\0");
- PrevSerialName = comboBox1.Text;
- #endif
- //MessageBox.Show();
- try
- {
- serialPort1.Open();
- }
- catch (Exception ea)
- {
- MessageBox.Show(ea.Message);
- }
- if (serialPort1.IsOpen)
- {
- try
- {
- Controller_TextLoad("\nPort Open Connect!!!");
- }
- 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";
- */
- ////////////////////
- }
-
- private void Button_Stop_Click(object sender, EventArgs e)
- {
- try
- {
- serialPort1.Close();
- Controller_TextLoad("\nPort Closed!!! ");
- }
- catch { }
-
- // Initialize = 0;
- //Serial on/off Button의 보이고 안보이게 하기
- Button_Start.Enabled = true; //on 기능 나타남
- Button_Start.Visible = true; //on 버튼 나타남
- Button_Stop.Enabled = false; //off 기능 사라짐
- Button_Stop.Visible = false; //off 버튼 사라짐
- SerialFormEnagleChoice(true); //serial 설정버튼 on
- }
- private void Start_Clear_Click(object sender, EventArgs e)
- {
- richTextBox1.Text = "";
- }
- private void comboBox1_Click(object sender, EventArgs e)
- {
-
- }
- private void button1_Click(object sender, EventArgs e)
- {
- comboBox1.Items.Clear();
- SerialPort_Get();
- }
- private void comboBox1_MouseClick(object sender, MouseEventArgs e)
- {
- comboBox1.DataSource = null;
- comboBox1.Items.Clear();
- SerialPort_Get();
- }
- }
- }
|