private void frmPreview_Load(object sender, System.EventArgs e) { try { f_LoadThum(); //f_ResetHinhIn(); //chkHI_1.Checked=false; //chkHI_2.Checked=false; lbi_Click(pt.Controls[0], null); } catch { } lbView.Focus(); }
public void Create_Message_On_Status_Bar(String Message_String, bool Alert_Allowed = true, bool Set_Focus = true) { if (Alert_Allowed) { Message_String = DateTime.Now.ToString() + " : " + Message_String; } Action New_Action = (new Action(() => { Label New_Btn_Box = new System.Windows.Forms.Label(); New_Btn_Box.Size = new Size(1074, 20); New_Btn_Box.Location = new Point(4 - Nest_Trader_Form.Nest_Trader_Form_Instance.Status_Page_Tab.HorizontalScroll.Value, 26 * Staus_Message_Lines_Cnt + 7 - Nest_Trader_Form.Nest_Trader_Form_Instance.Status_Page_Tab.VerticalScroll.Value); Staus_Message_Lines_Cnt++; New_Btn_Box.FlatStyle = FlatStyle.Popup; New_Btn_Box.BackColor = Color.MistyRose; New_Btn_Box.ForeColor = Color.Black; New_Btn_Box.Visible = true; New_Btn_Box.Text = Message_String; New_Btn_Box.TextAlign = ContentAlignment.MiddleLeft; // Nest_Trader_Form.Nest_Trader_Form_Instance.Status_Page_Tab.Controls.Add(New_Btn_Box); if (Set_Focus) { New_Btn_Box.Focus(); } Nest_Trader_Form.Nest_Trader_Form_Instance.Message_Log_Buffer += Message_String + "\r\n"; if (Alert_Allowed) { Start_Audio_Alert(); Start_Pop_UP_Alert("Nest Trader - Plugin", Message_String); } })); if (Nest_Trader_Form.Nest_Trader_Form_Instance.InvokeRequired) { Nest_Trader_Form.Nest_Trader_Form_Instance.Invoke(New_Action); } else { New_Action(); } }
public void Execute() { if (txtUsuario1.Focused) { txtUsuario2.Focus(); } else { txtUsuario1.Focus(); } _uiController.Execute(); }
public bool EsDouble(System.Windows.Forms.Label milabel) { double aux; if (double.TryParse(milabel.Text, out aux)) { return(true); } else { MessageBox.Show("Este Campo Solo Admite Numeros", "Mensaje Usuario", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); milabel.Focus(); return(false); } }
/// <summary> /// Imports masters tapes from file. /// </summary> /// <param name="worker">The worker.</param> /// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param> private void ImportMasters(BackgroundWorker worker, DoWorkEventArgs e) { Stream importStream = null; //Master List import, has a popup to enter Master Tape to add to List<MasterListValues> masterListValues = DataBaseControls.GetAllMasterListItems(); string[] cameraValues = commonMethod.CameraDropdownItems(); string masterTapeName = ""; string cameraMasterName = ""; bool addMasters = false; //create a new form for user to enter tape name Form masterPrompt = new Form(); masterPrompt.Height = 200; masterPrompt.Width = 500; masterPrompt.SizeGripStyle = SizeGripStyle.Hide; masterPrompt.FormBorderStyle = FormBorderStyle.FixedSingle; masterPrompt.StartPosition = FormStartPosition.CenterScreen; masterPrompt.Text = "Enter Tape Name"; //Set up items to add to popup box Label textLabel = new Label() { Left = 50, Top = 20, Text = "Master Archive to Import" }; ComboBox inputBox = new ComboBox() { Left = 50, Top = 50, Width = 400 }; //add items to combobox foreach (MasterListValues values in masterListValues) { inputBox.Items.Add(values.MasterArchive); } inputBox.SelectedIndex = 0; //add media combobox ComboBox mediaCombo = new ComboBox() { Left = 50, Top = 75, Width = 200 }; //add items to combobox foreach (string mediaValue in cameraValues) { mediaCombo.Items.Add(mediaValue); } mediaCombo.SelectedIndex = 1; mediaCombo.KeyPress += (senderCombo, eCombo) => { eCombo.Handled = true; }; mediaCombo.SelectedIndexChanged += (senderCombo, eCombo) => { textLabel.Focus(); }; //Check for names in the filename #region Check for names in File try { //check to make sure there is something selected if (!ofd.FileName.Equals(string.Empty)) { //get name of file without extension string nameFile = Path.GetFileNameWithoutExtension(ofd.FileName); //get index of the word master int index = nameFile.ToLower().IndexOf("master"); if(index != -1) { //get substring to include "master ddd" nameFile = nameFile.Substring(index); //check to make sure the last character is a digit while (!char.IsDigit(nameFile[nameFile.Length - 1])) { nameFile = nameFile.Remove(nameFile.Length - 1, 1); } //convert name to lowercasse and then camelcase TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; nameFile = textInfo.ToTitleCase(nameFile.ToLower()); //add name of master tape if not included if (!inputBox.Items.Contains(nameFile)) { inputBox.Items.Add(nameFile); } inputBox.Text = nameFile; } } } catch { Debug.WriteLine("Error in master gather"); } //check if there is a media defined in the name using all combobox items try { //check to make sure there is something selected if (!ofd.FileName.Equals(string.Empty)) { //get name of file without extension foreach (string obj in mediaCombo.Items) { Debug.WriteLine("In media for loop"); if (!obj.ToLower().Equals("other")) { Debug.WriteLine("Does not equal other"); //string[] mediaItems = mediaCombo.DataSource.t string nameFile = Path.GetFileNameWithoutExtension(ofd.FileName); //get index of the word master int index = nameFile.ToLower().IndexOf(obj.ToLower()); //add name of master tape if not included if (index != -1) { Debug.WriteLine("Does not equal -1"); mediaCombo.Text = obj; break; } } } } } catch { Debug.WriteLine("Error in media gather"); } #endregion //Set up buttons to add Button confirmation = new Button() { Text = "OK", Left = 240, Width = 100, Top = 120 }; Button cancelButton = new Button() { Text = "Cancel", Left = 350, Width = 100, Top = 120 }; //button actions cancelButton.Click += (senderPrompt, ePrompt) => { addMasters = false; masterPrompt.Close(); }; confirmation.Click += (senderPrompt, ePrompt) => { addMasters = true; masterTapeName = inputBox.Text; cameraMasterName = mediaCombo.Text; masterPrompt.Close(); }; //Add items to form masterPrompt.Controls.Add(textLabel); masterPrompt.Controls.Add(inputBox); masterPrompt.Controls.Add(mediaCombo); masterPrompt.Controls.Add(confirmation); masterPrompt.Controls.Add(cancelButton); masterPrompt.ShowDialog(); //Add entries or Cancel depending on button clicked if (addMasters) { //gets extension of the file and acts accordingly switch (GetExtensionOfFile(ofd)) { case "csv": UpdateStatusBarBottom("Importing " + masterTapeName + " Entries"); DataBaseControls.AddMasterTapesFromFile(worker, importStream, ofd, masterTapeName, commonMethod.GetCameraNumber(cameraMasterName)); break; case "txt": ofd.FileName = @"" + TempConvertToCSV(ofd); UpdateStatusBarBottom("Importing " + masterTapeName + " Entries"); DataBaseControls.AddMasterTapesFromFile(worker, importStream, ofd, masterTapeName, commonMethod.GetCameraNumber(cameraMasterName), true); break; case "doc": case "docx": ofd.FileName = @"" + ConvertWordToCSVFile(ofd); UpdateStatusBarBottom("Importing " + masterTapeName + " Entries"); DataBaseControls.AddMasterTapesFromFile(worker, importStream, ofd, masterTapeName, commonMethod.GetCameraNumber(cameraMasterName), true); break; default: Debug.WriteLine("File was not a txt, doc, docx, or csv"); break; } } else { worker.CancelAsync(); if (worker.CancellationPending) { e.Cancel = true; return; } } }
public void OneClickComboBoxCell () { Form form = null; try { // Create a form, a text label, and a data-grid-view. form = new Form (); Label label = new Label (); label.Text = "Label"; label.Parent = form; ClickableDataGridView dgv = new ClickableDataGridView (); dgv.Parent = form; // Create a combo-box column. DataGridViewComboBoxColumn cbCol = new DataGridViewComboBoxColumn (); cbCol.HeaderText = "Name"; dgv.Columns.Add (cbCol); // .NET requires that all possible values for combo-boxes // in a column are added to the column. cbCol.Items.Add ("Item1"); cbCol.Items.Add ("Item2"); cbCol.Items.Add ("Item3"); cbCol.Items.Add ("Item4"); // Set up the contents of the data-grid. dgv.Rows.Add ("Item1"); dgv.Rows.Add ("Item2"); // Select the cell. dgv.CurrentCell = dgv.Rows[0].Cells[0]; // Focus the data-grid-view. (Without this, its Leave // event won't get called when something outside of the // data-grid-view gets focused.) dgv.Focus (); // Show the form, let it draw. form.Show (); Application.DoEvents (); // Locate the drop-down button. (This code is taken from mono-winforms, // from the private method DataGridViewComboBoxCell.CalculateButtonArea(), // and was then hacked mercilessly.) Rectangle button_area = Rectangle.Empty; { int border = 3 /* ThemeEngine.Current.Border3DSize.Width */; const int button_width = 16; Rectangle text_area = dgv.GetCellDisplayRectangle (0, 0, false); button_area.X = text_area.Right - button_width - border; button_area.Y = text_area.Y + border; button_area.Width = button_width; button_area.Height = text_area.Height - 2 * border; } // Click on the drop-down button. int x = button_area.X + (button_area.Width / 2); int y = button_area.Y + (button_area.Height / 2); if (Environment.OSVersion.Platform == PlatformID.Win32NT && Type.GetType ("Mono.Runtime") == null) { // Calling OnMouseDownInternal () in Win32 doesn't work. // My best guess as to why is that the WinForms ComboBox // is a wrapper around the ComCtl control, e.g. similar // to the reason that Paint event-handlers don't work on // TreeView. So we go through all this rigamarole to // simulate a mouse click. // First, get the location of the desired mouse-click, in // data-grid-view coordinates. Win32Point ptGlobal = new Win32Point (); ptGlobal.x = x + dgv.Location.X; ptGlobal.y = y + dgv.Location.Y; // Convert that to screen coordinates. ClientToScreen (form.Handle, ref ptGlobal); // Move the mouse-pointer there. (Yes, this really appears // to be necessary.) SetCursorPos (ptGlobal.x, ptGlobal.y); // Convert screen coordinates to mouse coordinates. ptGlobal.x *= (65535 / SystemInformation.VirtualScreen.Width); ptGlobal.y *= (65535 / SystemInformation.VirtualScreen.Height); // Finally, fire a mouse-down and mouse-up event. mouse_event (MOUSEEVENTF_LEFTDOWN|MOUSEEVENTF_ABSOLUTE, ptGlobal.x, ptGlobal.y, 0, 0); mouse_event (MOUSEEVENTF_LEFTUP|MOUSEEVENTF_ABSOLUTE, ptGlobal.x, ptGlobal.y, 0, 0); // Let the system process these events. Application.DoEvents (); } else { // And this is how the same code is done under Linux. // (No one should wonder why I prefer Mono to MS Windows .NET ;-) MouseEventArgs me = new MouseEventArgs (MouseButtons.Left, 1, x, y, 0); DataGridViewCellMouseEventArgs cme = new DataGridViewCellMouseEventArgs (0, 0, x, y, me); dgv.OnMouseDownInternal (cme); dgv.OnMouseUpInternal (cme); } // Make sure that created an editing control. ComboBox cb = dgv.EditingControl as ComboBox; Assert.AreNotEqual (null, cb, "1-1"); // Make sure that dropped down the menu. Assert.AreEqual (true, cb.DroppedDown, "1-2"); // Close the menu. cb.DroppedDown = false; // Change the selection on the menu. cb.SelectedIndex = 2 /* "Item3" */; // Leave the data-grid-view. label.Focus (); // That should have ended editing and saved the value. string cellValue = (string)(dgv.Rows[0].Cells[0].FormattedValue); Assert.AreEqual ("Item3", cellValue, "1-3"); } finally { if (form != null) form.Close (); } }
private void sendbt() { if (bflag == true && bdll == "BTLibCs") { CalibCs.BTLibCs.BTLib_Initialize(); IntPtr btest = CalibCs.SerialFuncCs.CreateFile(com + ":", CalibCs.SerialFuncCs.GENERIC_WRITE | CalibCs.SerialFuncCs.GENERIC_READ, 0, IntPtr.Zero, CalibCs.SerialFuncCs.OPEN_EXISTING, CalibCs.SerialFuncCs.FILE_ATTRIBUTE_NORMAL, IntPtr.Zero); if (btest != IntPtr.Zero) { CalibCs.SerialFuncCs.DCB portconfig = new CalibCs.SerialFuncCs.DCB(); bool test2 = CalibCs.SerialFuncCs.GetCommState(btest, ref portconfig); portconfig.BaudRate = SerialFuncCs.CBR_19200; portconfig.Flag32 |= SerialFuncCs.fBinary; portconfig.Parity = SerialFuncCs.NOPARITY; portconfig.ByteSize = 8; portconfig.StopBits = SerialFuncCs.ONESTOPBIT; test2 = CalibCs.SerialFuncCs.SetCommState(btest, ref portconfig); int licznik = 0; uint modemstat = 0; while (modemstat != 176 && licznik != 30) { licznik += 1; label1.Text = "CZEKAM NA PO£¥CZENIE 30 sekund: " + licznik.ToString(); label1.Refresh(); label1.Focus(); System.Threading.Thread.Sleep(1000); SerialFuncCs.GetCommModemStatus(btest, ref modemstat); } if (licznik >= 30) { SerialFuncCs.CloseHandle(btest); CalibCs.BTLibCs.BTLib_DeInitialize(); label1.Text = "KONIEC CZASU"; } else { System.IO.FileStream file = new FileStream(ufile, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[file.Length]; file.Read(buffer, 0, buffer.Length); long lenght = file.Length; byte[] flaga = new byte[1]; flaga[0] = 1; byte[] bytec = BitConverter.GetBytes(lenght); uint bytestw = Convert.ToUInt32(buffer.Length); uint byteswr = new uint(); label1.Text = "WYSY£AM"; label1.Focus(); label1.Refresh(); System.Threading.Thread.Sleep(3000); test2 = SerialFuncCs.WriteFile(btest, flaga, Convert.ToUInt32(flaga.Length), ref byteswr, IntPtr.Zero); System.Threading.Thread.Sleep(3000); test2 = SerialFuncCs.WriteFile(btest, bytec, Convert.ToUInt32(bytec.Length), ref byteswr, IntPtr.Zero); System.Threading.Thread.Sleep(3000); //pEvtMask = 0; //SerialFuncCs.WaitCommEvent(btest, ref pEvtMask, IntPtr.Zero); //label3.Text = pEvtMask.ToString(); //MessageBox.Show("Wyœlij2"); // pEvtMask = 0; // SerialFuncCs.WaitCommEvent(btest, ref pEvtMask, IntPtr.Zero); //label1.Text = pEvtMask.ToString();; //while(pEvtMask != SerialFuncCs.EV_TXEMPTY) //{ //} //status_l.Text = "WYSY£ANIE"; test2 = SerialFuncCs.WriteFile(btest, buffer, bytestw, ref byteswr, IntPtr.Zero); System.Threading.Thread.Sleep(2000); flaga[0] = 3; test2 = SerialFuncCs.WriteFile(btest, flaga, Convert.ToUInt32(flaga.Length), ref byteswr, IntPtr.Zero); SerialFuncCs.CloseHandle(btest); CalibCs.BTLibCs.BTLib_DeInitialize(); //pEvtMask = 0; //label2.Text = pEvtMask.ToString(); label1.Text = "DANE WYS£ANE"; label1.Focus(); label1.Refresh(); file.Close(); testflag = 1; confirm_send(); } } else { MessageBox.Show("Niepoprawny port COM"); } } else if (bflag == true && bdll == "MSStack") { sendbtms(); } }
private void recive() { //string connectionString; //connectionString = "DataSource=Baza.sdf; Password=matrix1"; //SqlCeConnection cn = new SqlCeConnection(connectionString); if (bflag == true && bdll == "BTLibCs") { CalibCs.BTLibCs.BTLib_Initialize(); this.label1.Text = "OTWIERAM PORT"; label1.Refresh(); IntPtr btest = CalibCs.SerialFuncCs.CreateFile(com + ":", CalibCs.SerialFuncCs.GENERIC_WRITE | CalibCs.SerialFuncCs.GENERIC_READ, 0, IntPtr.Zero, CalibCs.SerialFuncCs.OPEN_EXISTING, CalibCs.SerialFuncCs.FILE_ATTRIBUTE_NORMAL, IntPtr.Zero); if (btest != IntPtr.Zero) { // MessageBox.Show("Com ok"); CalibCs.SerialFuncCs.DCB portconfig = new CalibCs.SerialFuncCs.DCB(); bool test2 = CalibCs.SerialFuncCs.GetCommState(btest, ref portconfig); if (test2 == true) { // MessageBox.Show("Get com st ok"); portconfig.BaudRate = SerialFuncCs.CBR_115200; portconfig.Flag32 |= SerialFuncCs.fBinary; portconfig.Parity = SerialFuncCs.NOPARITY; portconfig.ByteSize = 8; portconfig.StopBits = SerialFuncCs.ONESTOPBIT; test2 = CalibCs.SerialFuncCs.SetCommState(btest, ref portconfig); if (test2 == true) { byte[] bytecount = new byte[1024]; uint bytestw = new uint(); uint byteswr = new uint(); uint pEvtMask = SerialFuncCs.EV_RXCHAR; uint pEvtMask2 = SerialFuncCs.EV_RXCHAR; uint CTS = SerialFuncCs.EV_CTS; SerialFuncCs.WaitCommEvent(btest, ref pEvtMask, IntPtr.Zero); System.IO.FileStream file = new FileStream(dfile, FileMode.Create, FileAccess.Write); byte[] flaga = new byte[1]; flaga[0] = 0; int licznik = 0; uint modemstat = 0; while (modemstat != 176 && licznik != 30) { licznik += 1; label1.Text = "CZEKAM NA PO£¥CZENIE 30 sekund: " + licznik.ToString(); label1.Focus(); System.Threading.Thread.Sleep(1000); label1.Refresh(); SerialFuncCs.GetCommModemStatus(btest, ref modemstat); } if (licznik >= 30) { file.Close(); CalibCs.BTLibCs.BTLib_DeInitialize(); SerialFuncCs.CloseHandle(btest); label1.Text = "KONIEC CZASU"; label1.Refresh(); } else { // // if (devstat == "Err") // { // flaga[0] = 5; // // } this.label1.Text = "CZEKAM NA DANE"; label1.Refresh(); test2 = SerialFuncCs.WriteFile(btest, flaga, Convert.ToUInt32(flaga.Length), ref byteswr, IntPtr.Zero); System.Threading.Thread.Sleep(400); test2 = SerialFuncCs.WriteFile(btest, impdate, 16, ref byteswr, IntPtr.Zero); System.Threading.Thread.Sleep(1000); test2 = SerialFuncCs.ReadFile(btest, bytecount, Convert.ToUInt32(bytecount.Length), ref byteswr, IntPtr.Zero); uint lenght = BitConverter.ToUInt32(bytecount, 0); this.label1.Text = "ODBIERAM DANE: " + (lenght / 1024).ToString() + " Kb"; label1.Refresh(); byte[] buffer = new byte[lenght]; SerialFuncCs.WaitCommEvent(btest, ref pEvtMask2, IntPtr.Zero); test2 = SerialFuncCs.ReadFile(btest, buffer, Convert.ToUInt32(buffer.Length), ref byteswr, IntPtr.Zero); flaga[0] = 2; test2 = SerialFuncCs.WriteFile(btest, flaga, Convert.ToUInt32(flaga.Length), ref byteswr, IntPtr.Zero); SerialFuncCs.CloseHandle(btest); CalibCs.BTLibCs.BTLib_DeInitialize(); this.label1.Text = "ZAPISUJE DANE: " + (lenght / 1024).ToString() + "Kb " + "PROSZÊ CZEKAÆ"; label1.Refresh(); file.Write(buffer, 0, Convert.ToInt32(lenght)); file.Close(); this.label1.Text = "DANE ZAPISANE"; label1.Refresh(); } } else { } } } else { MessageBox.Show("Niepoprawny port com"); this.Close(); } } else if (bflag == true && bdll == "MSStack") { recivebtms(); } //SqlCeCommand cmd6 = new SqlCeCommand("UPDATE opcje SET devstat = 'Err')", cn); //cmd6.Prepare(); //cmd6.ExecuteNonQuery(); // cn.Close(); }
private void lbNoteName_MouseDown(object sender, MouseEventArgs e) { lbNameChoose = (Label)sender; xNote = e.X; yNote = e.Y; xNoteMove = lbNameChoose.Left; yNoteMove = lbNameChoose.Top; lbNameChoose.Focus(); }
/// <summary> /// Seleccionar una imagen dentro del componente, a partir del nombre de la misma /// </summary> /// <param name="pRutaImagen"></param> public void SeleccionarImagen( string pRutaImagen) { int mIndice = -1; for (int i = 0; i < this.ListaImagenes.Count; i++) if (this.ListaImagenes.ElementAt(i).ToLower() == pRutaImagen.ToLower()) mIndice = i; if (mIndice >= 0) { DeseleccionarImagen(); iPBoxSeleccionado = (PictureBox)this.Controls.Find("PictureBox" + mIndice.ToString() , true)[0]; iPBoxSeleccionado.Focus(); if (this.labels) { iLabelSeleccionado = (Label)this.Controls.Find("LabelPictureBox" + mIndice.ToString(), true)[0]; iLabelSeleccionado.BackColor = Color.Firebrick; iLabelSeleccionado.Focus(); } } }
/// <summary> /// 将考勤记录导入预备表中. /// </summary> /// <param name="xlsFilePath"></param> /// <param name="randomStr"></param> /// <param name="pb"></param> /// <returns></returns> public static MSG Import_Record_To_Preparative_Table(string xlsFilePath, string randomStr, System.Windows.Forms.Label lblPrompt, ProgressBar pb, System.Windows.Forms.Label lblResult) { int pbLength = 0; MSG msg = new MSG(); //用于确定本月最后一天. Stack <int> sDate = new Stack <int>(); Queue <AttendanceR> qAttendanceR = new Queue <AttendanceR>(); AttendanceR.Random_Str = randomStr; //按指纹日期 string fingerPrintDate = String.Empty; //导入数据的行数. int affectedCount = 0; //行最大值. int rowsMaxCount = 0; int colsMaxCount = 0; Usual_Excel_Helper uEHelper = null; MyExcel myExcel = new MyExcel(xlsFilePath); //打开该文档。 myExcel.open(); //只获取第一个表格。 Worksheet ws = myExcel.getFirstWorkSheetAfterOpen(); AttendanceR.File_path = xlsFilePath; //行;列最大值 赋值. rowsMaxCount = ws.UsedRange.Rows.Count; colsMaxCount = ws.UsedRange.Columns.Count; pb.Value = 0; pb.Visible = true; lblPrompt.Visible = true; AttendanceR.Sheet_name = ws.Name; //判断首行是否为 考勤记录表;以此判断此表是否为考勤记录表. string A1Str = ((Range)ws.Cells[1, 1]).Text.ToString().Trim().Replace("\n", "").Replace("\r", "").Replace(" ", ""); if (String.IsNullOrEmpty(A1Str)) { msg.Msg = "工作表的A1单元格不能为空!"; msg.Flag = false; myExcel.close(); return(msg); } //如果A1Str的内容不包含"考勤记录表"5个字。 if (!A1Str.Contains("考勤记录表")) { msg.Msg = "A1内容未包含'考勤记录表'"; msg.Flag = false; myExcel.close(); return(msg); } #region 判断名称中是否区分了考勤记录。 string Seq_Attendance_Record = string.Empty; int indexOfFullStop = xlsFilePath.LastIndexOf("."); Seq_Attendance_Record = xlsFilePath.Substring(indexOfFullStop - 1, 1); if (!CheckPattern.CheckNumber(Seq_Attendance_Record)) { msg.Msg = "考勤记录表名称请以数字结尾!"; msg.Flag = false; myExcel.close(); return(msg); } #endregion string excelName = Usual_Excel_Helper.getExcelName(xlsFilePath); AttendanceR.Prefix_Job_Number = excelName.Substring(excelName.Length - 1, 1).ToCharArray()[0]; string C3Str = ((Range)ws.Cells[3, 3]).Text.ToString().Trim(); // \0: 表空字符. if (String.IsNullOrEmpty(C3Str)) { msg.Msg = "异常: 考勤时间为空!"; msg.Flag = false; myExcel.close(); return(msg); } // string[] ArrayC3 = C3Str.Split('~'); if (ArrayC3.Length == 0) { msg.Msg = "异常: 考勤时间格式变更!"; msg.Flag = false; myExcel.close(); return(msg); } AttendanceR.Start_date = ArrayC3[0].ToString().Trim(); AttendanceR.End_date = ArrayC3[1].ToString().Trim(); //制表时间: L3 3行12列. string L3Str = ((Range)ws.Cells[3, 12]).Text.ToString().Trim(); if (String.IsNullOrEmpty(L3Str)) { msg.Msg = "异常: 制表时间为空!"; msg.Flag = false; myExcel.close(); return(msg); } //制表时间. AttendanceR.Tabulation_time = L3Str; //检查第4行是否为;考勤时间: string A4Str = ((Range)ws.Cells[4, 1]).Text.ToString().Trim(); if (!"1".Equals(A4Str, StringComparison.CurrentCultureIgnoreCase)) { msg.Msg = "异常: 第四行已变更!"; msg.Flag = false; myExcel.close(); return(msg); } uEHelper = new Usual_Excel_Helper(ws); //此刻不能删除,只是获取行号。 Queue <Range> rangeToDelQueue = new Queue <Range>(); //判断是否有空行。 for (int i = 5; i <= rowsMaxCount; i++) { if (uEHelper.isBlankRow(i)) { //只要上一列不是 //删除掉此行。 //判断上一行中的A列是否为工号。 string temp = uEHelper.getSpecificCellValue("A" + (i - 1).ToString()); if ("工号:".Equals(temp)) { //本行为空,上一行为工号行,则也统计。 continue; } //本行,为空,上一行非工号行。则删除本行。 Range rangeToDel = (Microsoft.Office.Interop.Excel.Range)uEHelper.WS.Rows[i, System.Type.Missing]; //不为工号 rangeToDelQueue.Enqueue(rangeToDel); } ; } Range rangeToDelete; //开始删除空行。 while (rangeToDelQueue.Count > 0) { rangeToDelete = rangeToDelQueue.Dequeue(); rangeToDelete.Delete(XlDeleteShiftDirection.xlShiftUp); } ; rowsMaxCount = ws.UsedRange.Rows.Count; //进度条长度增加。 pbLength += colsMaxCount; pbLength += (colsMaxCount * (rowsMaxCount - 5 + 1)); pb.Maximum = pbLength; //入队列值0 sDate.Push(0); //显示进度条。 //考勤表中第4行,某月的最大考勤天数。 lblPrompt.Text = excelName + ",正在读取:"; int actualMaxDay = 0; //开始循环 for (int i = 1; i <= colsMaxCount; i++) { A4Str = ((Range)ws.Cells[4, i]).Text.ToString(); //碰到第4行某列为空,退出循环。 if (String.IsNullOrEmpty(A4Str)) { break; } int aDate = 0; //对A4Str进行分析. if (!Int32.TryParse(A4Str, out aDate)) { msg.Msg = String.Format(@"异常: 考勤日期行第{0}列出现非数字内容!", aDate); msg.Flag = false; myExcel.close(); return(msg); } pb.Value++; //判断新增的日期是否大于上一个. if (aDate <= sDate.Peek()) { //跳出循环. break; } actualMaxDay++; sDate.Push(aDate); } //取其中的最小值。 colsMaxCount = Math.Min(sDate.Count - 1, actualMaxDay); //考勤日期 fingerPrintDate = AttendanceR.Start_date.Substring(0, 7).Replace('/', '-'); string tempStr = string.Empty; //开始循环 for (int colIndex = 1; colIndex <= colsMaxCount; colIndex++) { //从第5行开始. //奇数;偶数行共用一个对象. AttendanceR AR = null; for (int rowIndex = 5; rowIndex <= rowsMaxCount; rowIndex++) { //如果行数为奇数则为工号行. if (rowIndex % 2 == 1) { //工号行. //取工号 AR = new AttendanceR(); AR.Job_number = ((Range)ws.Cells[rowIndex, 3]).Text.ToString().Trim(); //自行拼凑AR. AR.combine_Job_Number(); //取姓名: K5 AR.Name = ((Range)ws.Cells[rowIndex, Usual_Excel_Helper.getColIndexByStr("K")]).Text.ToString().Trim(); //取部门: U5 AR.Dept = ((Range)ws.Cells[rowIndex, Usual_Excel_Helper.getColIndexByStr("U")]).Text.ToString().Trim(); //部门为空,则填充为NULL; AR.Dept = !String.IsNullOrEmpty(AR.Dept) ? AR.Dept : "NULL"; //取日期.填充0; AR.Fingerprint_Date = fingerPrintDate + "-" + colIndex.ToString().PadLeft(2, '0'); } else { //偶数行取考勤结果. //上班时间. 如B10; tempStr = ((Range)ws.Cells[rowIndex, colIndex]).Text.ToString().Trim(); string tempFirstTime = String.Empty; string tempLastTime = String.Empty; if (!getFPTime(tempStr, out tempFirstTime, out tempLastTime)) { msg.Msg = string.Format(@"导入失败:表中第{0}行{1}列的按指纹时间格式不对!", rowIndex, colIndex); msg.Flag = false; myExcel.close(); return(msg); } ; AR.FPT_Fisrt_Time = String.IsNullOrEmpty(tempFirstTime) ? String.Empty : AR.Fingerprint_Date + " " + tempFirstTime; AR.FPT_Last_Time = String.IsNullOrEmpty(tempLastTime) ? String.Empty : AR.Fingerprint_Date + " " + tempLastTime; qAttendanceR.Enqueue(AR); } pb.Value++; } } //释放对象 myExcel.close(); System.Threading.Thread.Sleep(2000); GC.Collect(); GC.WaitForPendingFinalizers(); lblResult.Text = ""; lblResult.Visible = false; lblPrompt.Visible = false; lblPrompt.Text = ""; lblPrompt.Text = "提交数据: "; lblPrompt.Focus(); lblPrompt.Visible = true; pb.Maximum = qAttendanceR.Count; pb.Value = 0; #region //保存对象 while (qAttendanceR.Count > 0) { try { AttendanceR aR = qAttendanceR.Dequeue(); affectedCount += aR.import_AR_To_Preparative_Table(); pb.Value++; } catch (Exception ex) { MessageBox.Show(ex.ToString(), "提示:", MessageBoxButtons.OK, MessageBoxIcon.Error); msg.Msg = DirectoryHelper.getFileName(xlsFilePath) + ":导入失败; " + ex.ToString(); msg.Flag = false; return(msg); } } #endregion lblPrompt.Visible = false; //隐藏进度条。 pb.Visible = false; msg.Flag = true; msg.Msg = String.Format(@"导入完成;计{0}条.", affectedCount.ToString()); return(msg); }