| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503 | using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using NPOI.SS.UserModel.Charts;using NPOI.SS.Util;using NPOI.XSSF.UserModel;using OTSIncAReportApp;using OTSIncAReportApp._1_UI;using OTSIncAReportApp.DataOperation.DataAccess;using OTSCommon.Model;using OTSIncAReportApp.SysMgrTools;using OTSIncAReportGraph.Class;using OTSIncAReportGraph.OTSIncAReportGraphFuncation;using OTSIncAReportGrids.OTSIncAReportGridsFuncation;using OTSIncAReportMailInterface;using System;using System.Collections;using System.Collections.Generic;using System.Data;using System.Drawing;using System.Drawing.Imaging;using System.IO;using System.Linq;using System.Reflection;using System.Threading;using System.Windows.Forms;namespace OTSIncAReportGrids{    public partial class ParticlesGridDevidePage : UserControl    {        #region 枚举定义        /// <summary>        /// 样品台X轴方向        /// </summary>        enum OTS_X_AXIS_DIRECTION        {            LEFT_TOWARD = 0,            RIGHT_TOWARD = 1        }        /// <summary>        /// 样品台Y轴方向        /// </summary>        enum OTS_Y_AXIS_DIRECTION        {            UP_TOWARD = 0,            DOWN_TOWARD = 1        }        #endregion        //设置模拟数据表        public DataTable m_dt = new DataTable();        //底层操作类        OTSReportGridsFun m_OTSIncAReportGridsFun = null;        //进度条窗体        public Frm_UserProgress m_frm_userprogress;        //移动SEM到指定位置发生线程        private Thread m_mythread;        //记录线程是否已经运行完成的状态        private bool m_mythread_state = false;        //导出图像文件的路径        private string m_imagefilepath = "";        //显示元素列表        public List<string> m_list_elementscolname = null;        //单个数据源所拥有的列数,这里保存下来,供导出模块使用        public int m_oneresult_columncount = 0;        OTSImageDisHelp m_ReportFun = null;        private OTSImageDisHelp ReportFun { get => m_ReportFun; set => m_ReportFun = value; }        //多个数据源,每个数据源拥有的列数,这里保存下来,供分组使用        public List<int> m_list_oneresult_columncount;        //国际化        Language lan;        Hashtable table;        //测量结果        ResultFile result = null;        string str_SysType = "";//当前启动模式(夹杂物、清洁度)        //frmReMeasure frmReMeasure = new frmReMeasure();        frmReportConditionChoose m_condition;        FieldData fieldData;        DataTable particlesAll;        DataTable particles;        ParticleData Particledata;        UserLibraryData userLibrary;        DataTable userLibraryData;        NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();        enum SelItem        {            analyticalParticle=0,            selectParticles=1,            otherParticles=2,            MergeParticles=3        }        #region 分页器相关        #region 分页字段和属性        string condition = "";        public string FileName = null;        private int pageIndex = 1;        /// <summary>        /// 当前页面        /// </summary>        public virtual int PageIndex        {            get { return pageIndex; }            set { pageIndex = value; }        }        private int pageSize = 20;        /// <summary>        /// 每页记录数        /// </summary>        public virtual int PageSize        {            get { return pageSize; }            set { pageSize = value; }        }        //string OrderFunction = "fieldid,particleid";        private int recordCount = 0;        /// <summary>        /// 总记录数        /// </summary>        public virtual int RecordCount        {            get { return recordCount; }            set { recordCount = value; }        }        private int pageCount = 0;        /// <summary>        /// 总页数        /// </summary>        public int PageCount        {            get            {                pageCount = GetPageCount();                return pageCount;            }        }        /// <summary>        /// 计算总页数        /// </summary>        /// <returns></returns>        private int GetPageCount()        {            if (PageSize == 0)            {                return 0;            }            int pageCount = RecordCount / PageSize;            if (RecordCount % PageSize == 0)            {                pageCount = RecordCount / PageSize;            }            else            {                pageCount = RecordCount / PageSize + 1;            }            return pageCount;        }        #endregion        frmReportApp m_ReportApp;        ResultFile resultFile = null;        #endregion        public ParticlesGridDevidePage(frmReportApp ReportApp)        {            m_ReportApp = ReportApp;            m_condition = ReportApp.m_conditionChoose;            resultFile = ReportApp.m_rstDataMgr.CurResultFile;            ReportFun = new OTSImageDisHelp(resultFile);            string sou = m_condition.m_CurrentConditions[OTSIncAReportApp.OTSSampleReportInfo.OTS_REPORT_PROP_GRID_ITEMS.DATA_SOURCE].itemDisplayVal.ToString();            if (sou.Contains("+"))            {                result = m_ReportApp.m_rstDataMgr.ResultFilesList[0];            }            else            {                for (int i = 0; i < m_ReportApp.m_rstDataMgr.ResultFilesList.Count; i++)                {                    if (sou == m_ReportApp.m_rstDataMgr.ResultFilesList[i].anotherFileName.ToString())                    {                        result = m_ReportApp.m_rstDataMgr.ResultFilesList[i];                    }                }            }            //设置窗体的双缓冲,以保证大数据时拖动不卡            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true);            this.UpdateStyles();            InitializeComponent();            //利用反射设置DataGridView的双缓冲            Type dgvType = this.dgV_ParticlesDevidePage.GetType();            PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);            pi.SetValue(this.dgV_ParticlesDevidePage, true, null);        }        bool Init()        {            try            {                lan = new Language(this);                table = lan.GetNameTable(this.Name);                m_mythread_state = false;                m_mythread = new Thread(new ParameterizedThreadStart(Thread_GO));                //m_frm_userprogress = new Frm_UserProgress();                fieldData = new FieldData(result.FilePath);                Particledata = new ParticleData(result.FilePath);                str_SysType = ((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)result.ResultInfo["Sample"])["Members"])["MsrParams"])["SysType"].ToString();                if (str_SysType == "0:IncA")                {                    userLibraryData = null;                }                else                {                    string str_libraryName = ((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)result.ResultInfo["Sample"])["Members"])["MsrParams"])["STDName"].ToString();                    userLibrary = new UserLibraryData(str_libraryName);                    if (userLibrary.GetSqlHelper() != null)                    {                        userLibraryData = userLibrary.GetSubAttributeFromDatabase();                    }                    else                    {                        userLibraryData = null;                    }                }                //初始化底层操作类                m_OTSIncAReportGridsFun = new OTSReportGridsFun(m_ReportApp, this);                return true;            }            catch (Exception ex)            {                log.Error(ex.ToString());                return false;            }        }        private void ParticlesGridDevidePage_Load(object sender, EventArgs e)        {            if (!Init())            {                return;            }            ProgressStart();//进度条关闭通过cbB_PageSize.SelectedIndex事件            if (!UpdateTable())            {                return;            }            cbB_PageSize.Items.Add("20");            cbB_PageSize.Items.Add("100");            cbB_PageSize.Items.Add("500");            cbB_PageSize.Items.Add("1000");            cbB_PageSize.Items.Add("5000");            cbB_PageSize.Items.Add("All");            cbB_PageSize.SelectedIndex = 0;        }        #region 自定义方法        bool UpdateTable()        {            int sel = m_ReportApp.m_conditionChoose.m_conditionData.GetComboDownListIndexByItemName(OTSIncAReportApp.OTSSampleReportInfo.OTS_REPORT_PROP_GRID_ITEMS.PARTICE_LIST);            if (sel == 1)            {                List<Particle> selectParticles = m_ReportApp.GetSelectedParticles();                DataTable dtUelect = new DataTable();                dtUelect.Columns.Add("fieldid");                dtUelect.Columns.Add("particleid");                dtUelect.Columns.Add("AveGray");                dtUelect.Columns.Add("RectLeft");                dtUelect.Columns.Add("RectTop");                dtUelect.Columns.Add("RectWidth");                dtUelect.Columns.Add("RectHeight");                dtUelect.Columns.Add("Area");                dtUelect.Columns.Add("PosX");                dtUelect.Columns.Add("PosY");                dtUelect.Columns.Add("TypeId");                //dtUelect.Columns.Add("ElementNum");                dtUelect.Columns.Add("SegmentNum");                dtUelect.Columns.Add("SEMPosX");                dtUelect.Columns.Add("SEMPosY");                dtUelect.Columns.Add("XrayId");                dtUelect.Columns.Add("DMAX");                dtUelect.Columns.Add("DMIN");                dtUelect.Columns.Add("DPERP");                dtUelect.Columns.Add("PERIMETER");                dtUelect.Columns.Add("ORIENTATION");                dtUelect.Columns.Add("DINSCR");                dtUelect.Columns.Add("DMEAN");                dtUelect.Columns.Add("DELONG");                dtUelect.Columns.Add("DFERET");                dtUelect.Columns.Add("TypeName");                dtUelect.Columns.Add("TypeColor");                //dtUelect.Columns.Add("SubParticles");                dtUelect.Columns.Add("Element");                dtUelect.Columns.Add("Hardness");                dtUelect.Columns.Add("Density");                dtUelect.Columns.Add("Electrical_conductivity");                for (int i = 0; i < selectParticles.Count; i++)                {                    dtUelect.Rows.Add(selectParticles[i].FieldId, selectParticles[i].ParticleId, selectParticles[i].AveGray, selectParticles[i].RectLeft, selectParticles[i].RectTop, selectParticles[i].RectWidth, selectParticles[i].RectHeight, selectParticles[i].Area, selectParticles[i].PosX, selectParticles[i].PosX, selectParticles[i].TypeId, /*selectParticles[i].ElementNum,*/ selectParticles[i].SegmentNum, selectParticles[i].SEMPosX, selectParticles[i].SEMPosY, selectParticles[i].ParticleId, selectParticles[i].DMAX, selectParticles[i].DMIN, selectParticles[i].DPERP, selectParticles[i].PERIMETER, selectParticles[i].ORIENTATION, selectParticles[i].DINSCR, selectParticles[i].DMEAN, selectParticles[i].DELONG, selectParticles[i].DFERET, selectParticles[i].TypeName, selectParticles[i].TypeColor,/* "", */"", "", "", "");                }                if (userLibraryData != null)                {                    for (int i = 0; i < dtUelect.Rows.Count; i++)                    {                        DataRow[] dr = userLibraryData.Select("STDId=" + dtUelect.Rows[i]["TypeId"].ToString());                        if (dr.Length > 0)                        {                            dtUelect.Rows[i]["Hardness"] = System.Text.RegularExpressions.Regex.Replace(dr[0]["Hardness"].ToString(), @"[^\d.\d]", "");                            dtUelect.Rows[i]["Density"] = System.Text.RegularExpressions.Regex.Replace(dr[0]["Density"].ToString(), @"[^\d.\d]", "");                            dtUelect.Rows[i]["Electrical_conductivity"] = System.Text.RegularExpressions.Regex.Replace(dr[0]["Electrical_conductivity"].ToString(), @"[^\d.\d]", "");                        }                        else                        {                            dtUelect.Rows[i]["Hardness"] = "";                            dtUelect.Rows[i]["Density"] = "";                            dtUelect.Rows[i]["Electrical_conductivity"] = "";                        }                    }                }                else                {                    for (int i = 0; i < dtUelect.Rows.Count; i++)                    {                        dtUelect.Rows[i]["Hardness"] = "";                        dtUelect.Rows[i]["Density"] = "";                        dtUelect.Rows[i]["Electrical_conductivity"] = "";                    }                }                particlesAll = new DataTable();                particlesAll = dtUelect.Copy();                btn_Sel.Enabled = false;            }            else            {                //多次测试发现 读取数据库时间耗时长,但读取条数目对读取数据库时长影响不大,故此处直接读取所有数据库信息,以取代多次连接数据库方式,优化分页速度                particlesAll = new DataTable();                if (sel == (int)SelItem.analyticalParticle)                {                    //particlesAll = Particledata.GetInfoForPartucleDevidePage2(condition);                    particlesAll = Particledata.GetInfoForPartucleDevidePage_analyticalParticle(condition);                }                if (sel == (int)SelItem.otherParticles)                {                    particlesAll = Particledata.GetInfoForPartucleDevidePage_otherParticle(condition);                }                if (sel == (int)SelItem.MergeParticles)                {                    particlesAll = Particledata.GetInfoForPartucleDevidePage_mergeParticles(condition);                }                particlesAll.Columns.Add("Hardness");                particlesAll.Columns.Add("Density");                particlesAll.Columns.Add("Electrical_conductivity");                if (userLibraryData != null)                {                    for (int i = 0; i < particlesAll.Rows.Count; i++)                    {                        DataRow[] dr = userLibraryData.Select("STDId=" + particlesAll.Rows[i]["TypeId"].ToString());                        if (dr.Length > 0)                        {                            particlesAll.Rows[i]["Hardness"] = dr[0]["Hardness"].ToString();                            particlesAll.Rows[i]["Density"] = dr[0]["Density"].ToString();                            particlesAll.Rows[i]["Electrical_conductivity"] = dr[0]["Electrical_conductivity"].ToString();                        }                        else                        {                            particlesAll.Rows[i]["Hardness"] = "";                            particlesAll.Rows[i]["Density"] = "";                            particlesAll.Rows[i]["Electrical_conductivity"] = "";                        }                    }                }                else                {                    for (int i = 0; i < particlesAll.Rows.Count; i++)                    {                        particlesAll.Rows[i]["Hardness"] = "";                        particlesAll.Rows[i]["Density"] = "";                        particlesAll.Rows[i]["Electrical_conductivity"] = "";                    }                }                                btn_Sel.Enabled = true;            }            if (particlesAll == null)            {                log.Error("There is an exception in the data of the database!");                #region 加载进度条进度部份结束                //加载完成设置鼠标为默认                this.Cursor = Cursors.Default;                //加载完成,关闭进度条                m_frm_userprogress.Close();                #endregion                return false;            }            DataTable elementchemistry = Particledata.GetElementChemistry();            for (int i = 0; i < particlesAll.Rows.Count; i++)            {                string str = "XRayId = " + particlesAll.Rows[i]["particleId"].ToString() + " and fieldid = " + particlesAll.Rows[i]["fieldid"].ToString();                DataRow[] drs = elementchemistry.Select(str);                string ConcatenatedString = "";                for (int j = 0; j < drs.Length; j++)                {                    ConcatenatedString += drs[j]["name"] + "-" + drs[j]["Percentage"] + ';';                }                particlesAll.Rows[i]["Element"] = ConcatenatedString;            }            return true;        }        /// <summary>        /// DataRow转换为DataTable        /// </summary>        /// <param name="dt"></param>        /// <param name="strWhere">筛选的条件</param>        /// <returns></returns>        public DataTable SreeenDataTable(DataTable dt, string strWhere)        {            if (dt.Rows.Count <= 0) return dt;        //当数据为空时返回            DataTable dtNew = dt.Clone();         //复制数据源的表结构            DataRow[] dr = dt.Select(strWhere);  //strWhere条件筛选出需要的数据!            for (int i = 0; i < dr.Length; i++)            {                dtNew.Rows.Add(dr[i].ItemArray);  // 将DataRow添加到DataTable中            }            return dtNew;        }        ///// <summary>        ///// DataRow转换为DataTable        ///// </summary>        ///// <param name="dt"></param>        ///// <param name="strWhere">筛选的条件</param>        ///// <returns></returns>        //public DataTable SreeenDataTable(DataTable dt, string strWhere)        //{        //    if (dt.Rows.Count <= 0) return dt;        //当数据为空时返回        //    DataTable dtNew = dt.Clone();         //复制数据源的表结构        //    DataRow[] dr = dt.Select(strWhere);  //strWhere条件筛选出需要的数据!        //    for (int i = 0; i < dr.Length; i++)        //    {        //        dtNew.Rows.Add(dr[i].ItemArray);  // 将DataRow添加到DataTable中        //    }        //    return dtNew;        //}        /// <summary>        /// 传入单颗颗粒的particle类对象,返回从field中抠取出的bitmap对象,抠取单颗颗粒        /// </summary>        /// <param name="in_cotsparticleclr"></param>        /// <returns></returns>        public Bitmap GetBitmapByParticle(string fieldImage, Rectangle offset_rect)        {            //然后将取出的数据,转换成Bitmap对象            Bitmap ls_bt = DrawFunction.ReadImageFile(fieldImage);            //为了能把整个颗粒显示完整            offset_rect.X = offset_rect.X - 5;            offset_rect.Y = offset_rect.Y - 5;            offset_rect.Width = offset_rect.Width + 10;            offset_rect.Height = offset_rect.Height + 10;            //防止计算偏差后,有坐标溢出现象            if (offset_rect.X < 0)                offset_rect.X = 0;            if (offset_rect.Y < 0)                offset_rect.Y = 0;            if (offset_rect.X + offset_rect.Width > ls_bt.Width)            {                offset_rect.Width = ls_bt.Width - offset_rect.X;            }            if (offset_rect.Y + offset_rect.Height > ls_bt.Height)            {                offset_rect.Height = ls_bt.Height - offset_rect.Y;            }            //            Bitmap new_ret_bp;            //防止为0后面计算出错            if (offset_rect.Width > 0 && offset_rect.Height > 0)            {                //最后通过list_showsegment组建成新的图片,进行返回                new_ret_bp = ls_bt.Clone(offset_rect, PixelFormat.Format8bppIndexed);            }            else            {                new_ret_bp = new Bitmap(offset_rect.Width, offset_rect.Height);            }            return new_ret_bp;        }        public Bitmap GetBitmapForBig(string sub, ParticleData fielddata, double xs)        {            string vs = "," + sub.Replace(':', '-') + ",";            DataTable dataTable = fielddata.GetParticleAll(vs);            if (dataTable.Rows.Count == 0)            {                return null;            }            string path = result.FilePath;            //内接矩形            double max_Y = Convert.ToInt64(dataTable.Rows[0]["FieldPosY"]) * xs - Convert.ToInt64(dataTable.Rows[0]["RectTop"]);            double max_X = Convert.ToInt64(dataTable.Rows[0]["FieldPosX"]) * xs + Convert.ToInt64(dataTable.Rows[0]["RectLeft"]);            double min_Y = max_Y;            double min_X = max_X;            //拼接field矩形            double MAX_Y = Convert.ToInt64(dataTable.Rows[0]["FieldPosY"]) * xs;            double MAX_X = Convert.ToInt64(dataTable.Rows[0]["FieldPosX"]) * xs;            double MIN_Y = MAX_Y;            double MIN_X = MAX_X;            foreach (DataRow item in dataTable.Rows)            {                //颗粒外接矩形                double lefttopX = Convert.ToInt64(item["FieldPosX"]) * xs + Convert.ToInt64(item["RectLeft"]);                if (lefttopX < min_X)                {                    min_X = lefttopX;                }                if (lefttopX + Convert.ToInt64(item["RectWidth"]) > max_X)                {                    max_X = lefttopX + Convert.ToInt64(item["RectWidth"]);                }                double lrfttopY = Convert.ToInt64(item["FieldPosY"]) * xs - Convert.ToInt64(item["RectTop"]);                if (max_Y < lrfttopY)                {                    max_Y = lrfttopY;                }                if (min_Y > lrfttopY - Convert.ToInt64(item["RectHeight"]))                {                    min_Y = lrfttopY - Convert.ToInt64(item["RectHeight"]);                }                //画布                double lefttopXH = Convert.ToInt64(item["FieldPosX"]) * xs;                if (lefttopXH > MAX_X)                {                    MAX_X = lefttopXH;                }                if (lefttopXH < MIN_X)                {                    MIN_X = lefttopXH;                }                double lrfttopYH = Convert.ToInt64(item["FieldPosY"]) * xs;                if (MAX_Y < lrfttopYH)                {                    MAX_Y = lrfttopYH;                }                if (MIN_Y > lrfttopYH)                {                    MIN_Y = lrfttopYH;                }            }            int WIDTH = Convert.ToInt32(MAX_X - MIN_X) + 1024;            int HEIGHT = Convert.ToInt32(MAX_Y - MIN_Y) + 768;            //构造最终的图片白板            Bitmap tableChartImage = new Bitmap(WIDTH, HEIGHT);            Graphics graph = Graphics.FromImage(tableChartImage);            //初始化这个大图            graph.DrawImage(tableChartImage, 0, 0);            int width = Convert.ToInt32(max_X - min_X);            int height = Convert.ToInt32(max_Y - min_Y);            int X = Convert.ToInt32(min_X - MIN_X);            int Y = Convert.ToInt32(MAX_Y - max_Y);            Rectangle rectangle = new Rectangle() { X = X, Y = Y, Width = width, Height = height };            foreach (DataRow item in dataTable.Rows)            {                string filePath = path + "\\FIELD_FILES\\";                string imagePath = filePath + "Field" + item["fieldid"].ToString() + ".bmp";                //然后将取出的数据,转换成Bitmap对象                Bitmap ls_bt = DrawFunction.ReadImageFile(imagePath);                int x = Convert.ToInt32(Convert.ToDouble(item["FieldPosX"]) * xs - MIN_X);                int y = System.Math.Abs(Convert.ToInt32(Convert.ToDouble(item["FieldPosY"]) * xs - MAX_Y));                try                {                    graph.DrawImage(ls_bt, x, y);                }                catch /*(Exception e)*/                {                    throw;                }            }            Bitmap bmap = tableChartImage.Clone(rectangle, PixelFormat.Format8bppIndexed);            return bmap;        }        private void BindDataGridView()        {            dgV_ParticlesDevidePage.Visible = false;            if (m_frm_userprogress.IsDisposed)            {                ProgressStart();            }            dgV_ParticlesDevidePage.Rows.Clear();            dgV_ParticlesDevidePage.Columns.Clear();            //从报告xml文件中加载,显示计算列,显示元素信息            string str_DefaultComputedColName = "", str_ElementsColName = "";            DataSet ds = XMLoperate.GetXmlData(Application.StartupPath + RptConfigFile.m_ReportMgrParamFile, "XMLData");            DataTable dt = ds.Tables["Member"];            foreach (DataRow element in dt.Rows)            {                string RegName = element["RegName"].ToString();                if (RegName == "DefaultComputedColName")                {                    str_DefaultComputedColName = element["strValue"].ToString();                }                if (RegName == "ElementsColName")                {                    str_ElementsColName = element["strValue"].ToString();                }            }            //获取需要显示的计算列            string[] strs = str_DefaultComputedColName.Split(',');            //列名            Dictionary<string, string> keyValues = new Dictionary<string, string>() { };            keyValues.Add("rowid", table["str4"].ToString());            keyValues.Add("TypeName", table["str6"].ToString());            keyValues.Add("ParticleImage", table["str5"].ToString());            keyValues.Add("FieldId", "FieldId");            keyValues.Add("ParticleId", "ParticleId");            keyValues.Add("SEMPosX", "SEMPosX");            keyValues.Add("SEMPosY", "SEMPosY");            for (int i = 0; i < strs.Count(); i++)            {                if (strs[i] == "ParticleCoordinate")                {                    keyValues.Add("PosX", "PosX");                    keyValues.Add("PosY", "PosY");                }                if (strs[i] == "Area")                {                    keyValues.Add("Area", table["str21"].ToString());                }                if (strs[i] == "EquivalentCircleDiameter")                {                    keyValues.Add("Equivalent", table["str22"].ToString());                }                if (strs[i] == "MaxDiameter")                {                    keyValues.Add("DMAX", table["str23"].ToString());                }                if (strs[i] == "MinDiameter")                {                    keyValues.Add("DMIN", table["str24"].ToString());                }                if (strs[i] == "DiameterRatio")                {                    keyValues.Add("DiameterRatio", table["str25"].ToString());                }                if (strs[i] == "FerretDiameter")                {                    keyValues.Add("DFERET", table["str26"].ToString());                }                if (strs[i] == "PERP")                {                    keyValues.Add("DPERP", table["str27"].ToString());                }                if (strs[i] == "PERI")                {                    keyValues.Add("PERIMETER", table["str28"].ToString());                }                if (strs[i] == "INSCR")                {                    keyValues.Add("DINSCR", table["str29"].ToString());                }                if (strs[i] == "MEAN")                {                    keyValues.Add("DMEAN", table["str30"].ToString());                }                if (strs[i] == "ELONG")                {                    keyValues.Add("DELONG", table["str31"].ToString());                }                if (strs[i] == "ASPECT_ELONG")                {                    keyValues.Add("ASPECT_ELONG", table["str32"].ToString());                }                if (strs[i] == "Orientation")                {                    keyValues.Add("ORIENTATION", table["str33"].ToString());                }                if (str_SysType == "1:CleannessA")                {                    if (strs[i] == "Hardness")                    {                        keyValues.Add("Hardness", table["str34"].ToString());                    }                    if (strs[i] == "Density")                    {                        keyValues.Add("Density", table["str35"].ToString());                    }                    if (strs[i] == "Electrical_conductivity")                    {                        keyValues.Add("Electrical_conductivity", table["str36"].ToString());                    }                }            }            keyValues.Add("Element", "Element");            Dictionary<string, string>.Enumerator en = keyValues.GetEnumerator();            for (int irow = 0; irow < keyValues.Count; irow++)            {                if (en.MoveNext())                {                    if (en.Current.Key == "ParticleImage")                    {                        DataGridViewImageColumn iconColumn = new DataGridViewImageColumn();                        iconColumn.Name = en.Current.Key;                        iconColumn.HeaderText = en.Current.Value;                        dgV_ParticlesDevidePage.Columns.Add(iconColumn);                    }                    else if (en.Current.Key == "Element")                    {                    }                    else                    {                        /*int columndid = */dgV_ParticlesDevidePage.Columns.Add(en.Current.Key, en.Current.Value);                    }                }            }            if (PageSize == -1)            {                PageSize = particlesAll.Rows.Count;            }            if (particlesAll == null)            {                return;            }            RecordCount = particlesAll.Rows.Count;            particles = particlesAll.Clone();            for (int fi = (PageIndex - 1) * pageSize; fi < PageIndex * pageSize; fi++)            {                if (fi > RecordCount - 1)                {                    break;                }                particles.ImportRow(particlesAll.Rows[fi]);            }            string particleM = "";            //获取需要显示的元素名            List<string> ElementTypeSort = new List<string>(str_ElementsColName.Split(',').ToList());//去重            for (int i = 0; i < ElementTypeSort.Count; i++)            {                dgV_ParticlesDevidePage.Columns.Add(ElementTypeSort[i], ElementTypeSort[i]);            }            double jd = 95f / (double)particles.Rows.Count;//计算进度刻度            string filePath = result.FilePath + "\\FIELD_FILES\\";            KeyValuePair<string, Bitmap> FieldImage = new KeyValuePair<string, Bitmap>();            for (int i = 0; i < particles.Rows.Count; i++)            {                //更新进度,每100条记录加载完,更新一次进度                if (i % 10 == 0)                    m_frm_userprogress.SetProgressValueAndText((int)(jd * i), "loading..");                Dictionary<string, string>.Enumerator enl = keyValues.GetEnumerator();                int add_rowindex = dgV_ParticlesDevidePage.Rows.Add();                dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[0].Value = (pageSize * (PageIndex - 1) + add_rowindex + 1).ToString();                for (int k = 0; k < keyValues.Count; k++)                {                    if (enl.MoveNext())                    {                        if (enl.Current.Key == "rowid")                        {                            //dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Value = i + 1;                        }                        if (enl.Current.Key == "ParticleImage")                        {                            if (particles.Columns.Contains("SubParticles"))                            {                                string subt = particles.Rows[i]["SubParticles"].ToString();                                if (subt != null && subt != "")                                {                                    double ScanFieldSize = Convert.ToDouble(((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)result.ResultInfo["Sample"])["Members"])["SEMDataMsr"])["ScanFieldSize"]);                                    string filePatht = result.FilePath + "\\FIELD_FILES\\";                                    string imagePatht = filePatht + "Field" + subt.Split(',')[0].Split(':')[0].ToString() + ".bmp";                                    //然后将取出的数据,转换成Bitmap对象                                    Bitmap tempbit = Particledata.ReadImageFile(imagePatht);                                    int pixw = tempbit.Width;                                    double xs = pixw / ScanFieldSize;                                    particleM = particleM + "," + subt;                                    Bitmap bmap = Particledata.GetBitmapForBig(subt, xs, result.FilePath, tempbit.Height, tempbit.Width);                                    if (bmap != null)                                    {                                        string[] str = subt.Split(',');                                        bmap.Tag = new List<string>() { str[0].Split(':')[0], str[0].Split(':')[1], particles.Rows[i]["TypeId"].ToString() };                                        dgV_ParticlesDevidePage.Rows[add_rowindex].Height = 150;                                        dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Value = bmap;                                        dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Style.BackColor = Color.Azure;                                        dgV_ParticlesDevidePage.Rows[add_rowindex].DefaultCellStyle.ForeColor = Color.Chocolate;                                    }                                    else                                    {                                        dgV_ParticlesDevidePage.Rows[add_rowindex].Height = 150;                                        dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Style.BackColor = Color.Azure;                                    }                                }                            }                            else                            {                                if (FieldImage.Key != particles.Rows[i]["fieldid"].ToString() || FieldImage.Value == null)                                {                                    string imagePath = filePath + "Field" + particles.Rows[i]["fieldid"].ToString() + ".bmp";                                    FieldImage = new KeyValuePair<string, Bitmap>(particles.Rows[i]["fieldid"].ToString(), Particledata.ReadImageFile(imagePath));                                }                                Rectangle rectangle = new Rectangle() { X = Convert.ToInt32(particles.Rows[i]["RectLeft"]), Y = Convert.ToInt32(particles.Rows[i]["RectTop"]), Width = Convert.ToInt32(particles.Rows[i]["RectWidth"]), Height = Convert.ToInt32(particles.Rows[i]["RectHeight"]) };                                Bitmap bmap = Particledata.GetBitmapByParticle(FieldImage.Value, rectangle);                                bmap.Tag = new List<string>() { particles.Rows[i]["FieldId"].ToString(), particles.Rows[i]["ParticleId"].ToString(), particles.Rows[i]["TypeId"].ToString(), particles.Rows[i]["XrayId"].ToString() };                                dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Value = bmap;                                dgV_ParticlesDevidePage.Rows[add_rowindex].Height = bmap.Height + 20;                            }                        }                        if (enl.Current.Key == "DiameterRatio")                        {                            double d = Convert.ToDouble(particles.Rows[i]["DMAX"]) / Convert.ToDouble(particles.Rows[i]["DMIN"]);                            dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Value = Math.Round(d, 2);                        }                        if (enl.Current.Key == "ASPECT_ELONG")                        {                            double d = Convert.ToDouble(particles.Rows[i]["DELONG"]) / Convert.ToDouble(particles.Rows[i]["DMEAN"]);                            dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Value = Math.Round(d, 2);                        }                        if (particles.Columns.Contains(enl.Current.Key))                        {                            double num = 0;                            if (double.TryParse(particles.Rows[i][enl.Current.Key].ToString(), out num))                            {                                dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Value = Math.Round(num, 2);                            }                            else if (enl.Current.Key == "Element")                            {                                List<string> elementtemp = new List<string>(ElementTypeSort);                                string[] strcbo = particles.Rows[i][enl.Current.Key].ToString().Split(';');                                for (int j = 0; j < strcbo.Length; j++)                                {                                    string[] str = strcbo[j].Split('-');                                    if (ElementTypeSort.Contains(str[0]))                                    { dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[str[0].ToString()].Value = Math.Round(double.Parse(str[1]), 2).ToString(); }                                    elementtemp.Remove(str[0].ToString());                                }                                foreach (var ele in elementtemp)                                {                                    dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[ele].Value = "0";                                }                            }                            else                            {                                dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Value = particles.Rows[i][enl.Current.Key];                            }                        }                        if (enl.Current.Key == "TypeName")                        {                            if (particles.Rows[i]["TypeId"].ToString() == "9")                            {                                dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Value = "Not Identified";                            }                        }                        if (enl.Current.Key == "Equivalent")                        {                            double dSize = Convert.ToDouble(particles.Rows[i]["Area"]);                            double Diameter = Math.Sqrt(dSize / Math.PI) * 2;                            dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Value = Math.Round(Diameter, 2);                        }                        if (enl.Current.Key == "Hardness")                        {                            string str = ChangeHardnessColor(particles.Rows[i]["Hardness"].ToString());                            {                                if (str == "#FF0000")                                {                                    dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Style.ForeColor = Color.Red;                                }                                dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[k].Value = particles.Rows[i]["Hardness"].ToString();                            }                        }                    }                }            }            #region 加载进度条进度部份结束            //加载完成设置鼠标为默认            this.Cursor = Cursors.Default;            string str8 = table["str8"].ToString();            m_frm_userprogress.SetProgressValueAndText(100, str8);            //加载完成,关闭进度条            m_frm_userprogress.Close();            #endregion            dgV_ParticlesDevidePage.Visible = true;        }        /// <summary>        /// 设置DataGridView样式        /// </summary>        private void SetDataGridViewStyle()        {            //用户不能调整标题的高度            dgV_ParticlesDevidePage.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;            //用户不能调整 行高            dgV_ParticlesDevidePage.AllowUserToResizeRows = false;            //点击选择整行            dgV_ParticlesDevidePage.SelectionMode = DataGridViewSelectionMode.FullRowSelect;            //居中显示            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();            dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;            dgV_ParticlesDevidePage.DefaultCellStyle = dataGridViewCellStyle1;            dgV_ParticlesDevidePage.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;            //再次重覆禁用拖动表头高度,居然有效果了            dgV_ParticlesDevidePage.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;            //设置grid可以复制            dgV_ParticlesDevidePage.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;            //设置每列的宽度            dgV_ParticlesDevidePage.Columns[0].Width = 40;//第一列序号的宽度设置一下吧,要不太丑            dgV_ParticlesDevidePage.Columns[1].Width = 150;            //dgV_ParticlesDevidePage.Columns[dgV_ParticlesDevidePage.Columns.Count - 1].Width = 450;            //dgV_ParticlesDevidePage.Columns[dgV_ParticlesDevidePage.Columns.Count - 1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;            //设置序号列不排序            dgV_ParticlesDevidePage.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;            //设置序号列不可以设置宽度            dgV_ParticlesDevidePage.Columns[0].Resizable = DataGridViewTriState.False;            dgV_ParticlesDevidePage.RowsDefaultCellStyle.BackColor = Color.Azure;        }        #endregion        #region 相关事件        private void ToolStripMenuItem1_Click(object sender, EventArgs e)        {            //复制整个表            CopyAll();        }        private void ToolStripMenuItem2_Click(object sender, EventArgs e)        {            //复制选择区域            CopySelected();        }        /// <summary>        /// 复制选择区域        /// </summary>        public void CopySelected()        {            //复制选择区域            object oo = dgV_ParticlesDevidePage.GetClipboardContent();            if (oo != null)                Clipboard.SetDataObject(dgV_ParticlesDevidePage.GetClipboardContent());        }        /// <summary>        /// 复制所有        /// </summary>        public void CopyAll()        {            dgV_ParticlesDevidePage.SelectAll();            Clipboard.SetDataObject(dgV_ParticlesDevidePage.GetClipboardContent());        }        /// <summary>        /// 以图像的方式将GridView进行截图        /// </summary>        public void CopyImage()        {            int height, width;            width = dgV_ParticlesDevidePage.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) + 2;            height = this.Height;            Bitmap image = new Bitmap(width, height);            dgV_ParticlesDevidePage.DrawToBitmap(image, new Rectangle(0, 0, width, height));            Clipboard.SetImage(image);        }        private void toolStripMenuItem4_Click(object sender, EventArgs e)        {            //对gridview进行截图            CopyImage();        }        private void dgV_ParticlesDevidePage_SortCompare(object sender, DataGridViewSortCompareEventArgs e)        {            //排序中            if (this.dgV_ParticlesDevidePage.Rows[e.RowIndex1].Tag != null && this.dgV_ParticlesDevidePage.Rows[e.RowIndex1].Tag.ToString() == "统计行")            {                //ROW1>ROW2                  e.SortResult = 1;                if (this.dgV_ParticlesDevidePage.SortOrder == SortOrder.Descending)                    e.SortResult = -1;                e.Handled = true;                return;            }            if (this.dgV_ParticlesDevidePage.Rows[e.RowIndex2].Tag != null && this.dgV_ParticlesDevidePage.Rows[e.RowIndex2].Tag.ToString() == "统计行")            {                //ROW1<ROW2                  e.SortResult = -1;                if (this.dgV_ParticlesDevidePage.SortOrder == SortOrder.Descending)                    e.SortResult = 1;                e.Handled = true;                return;            }        }        /// <summary>        /// 将OTS坐标转换为Sem 坐标        /// </summary>        /// <param name="POTSCoord"></param>        /// <returns></returns>        public Point ChangeOTSToSemCoord(Point POTSCoord)        {            //first if m_semstagedata is null to get stage inforation            Convert.ToDouble(((Dictionary<string, object>)result.ResultInfo["SEMStageData"])["scanFieldSize"]);            //after obtaining stage info,calc stage point data            Point ret_SEM_point = new Point();            // get center point, um            long xStart = Convert.ToInt64(((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)result.ResultInfo["SEMStageData"])["Members"])["XAxis"])["start"]);            long xEnd = Convert.ToInt64(((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)result.ResultInfo["SEMStageData"])["Members"])["XAxis"])["end"]);            long xCenter = (xStart + xEnd) / 2;            long yStart = Convert.ToInt64(((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)result.ResultInfo["SEMStageData"])["Members"])["YAxis"])["start"]);            long yEnd = Convert.ToInt64(((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)result.ResultInfo["SEMStageData"])["Members"])["YAxis"])["end"]);            long yCenter = (yStart + yEnd) / 2;            // delte = SEM - OTSa            long deltex = xCenter - 0;            long deltey = yCenter - 0;            int xdir = Convert.ToInt32(((Dictionary<string, object>)result.ResultInfo["SEMStageData"])["xAxisDir"]);            int ydir = Convert.ToInt32(((Dictionary<string, object>)result.ResultInfo["SEMStageData"])["yAxisDir"]);            if (xdir == (int)OTS_X_AXIS_DIRECTION.LEFT_TOWARD)            {                ret_SEM_point.X = -1 * (POTSCoord.X - Convert.ToInt32(deltex));            }            else if (xdir == (int)OTS_X_AXIS_DIRECTION.RIGHT_TOWARD)            {                ret_SEM_point.X = POTSCoord.X + Convert.ToInt32(deltex);            }            if (ydir == (int)OTS_Y_AXIS_DIRECTION.UP_TOWARD)            {                ret_SEM_point.Y = POTSCoord.Y + Convert.ToInt32(deltey);            }            else if (ydir == (int)OTS_Y_AXIS_DIRECTION.DOWN_TOWARD)            {                ret_SEM_point.Y = -1 * (POTSCoord.Y - Convert.ToInt32(deltey));            }            return ret_SEM_point;        }        #endregion        #region 获取向导出模块提供的DataTable和GridView对象        /// <summary>        /// 获取到该模块输出后形成的DataTable,和GridView        /// </summary>        /// <param name="out_dt"></param>        /// <param name="out_dg"></param>        public void GetDataTableAndGridView(out DataTable out_dt, out DataGridView out_dg)        {            out_dt = m_dt;            out_dg = this.dgV_ParticlesDevidePage;//同样通过 dgV_ParticlesDevidePage.Rows[add_rowindex].Cells[2].Value 来获取bitmap对象        }        #endregion        #region 连接电镜相关        /// <summary>        /// 移动SEM到指定位置线程函数        /// </summary>        private void Thread_GO(object in_obj)        {            if (m_mythread_state == false)            {                m_mythread_state = true;                Point sem_point = (Point)in_obj;                //第一步,连接电镜                m_OTSIncAReportGridsFun.Connection_ForParticlesGrid();                Thread.Sleep(500);                //第二步,移动到指定位置,先读取再设置                if (m_OTSIncAReportGridsFun.m_SEMConnectionState == true)                {                    m_OTSIncAReportGridsFun.MoveSemToPointXY_ForParticlesGrid(sem_point.X, sem_point.Y);                }                Thread.Sleep(1500);                //第三步,断开电镜连接                //m_OTSIncAReportGridsFun.DisConnectSEM_ForParticlesGrid();                //Thread.Sleep(500);                m_mythread_state = false;            }        }        #endregion        private void ToolStripMenuItem_exportzoomimagefile_Click(object sender, EventArgs e)        {            //导出放大图像            FolderBrowserDialog fbd = new FolderBrowserDialog();            if (fbd.ShowDialog() == DialogResult.OK)            {                m_imagefilepath = fbd.SelectedPath;                for (int i = 0; i < m_dt.Rows.Count; i++)                {                    Bitmap ls_bp = new Bitmap(1, 1);                    ls_bp = (Bitmap)m_dt.Rows[i][1];                    string strPath = m_imagefilepath + "\\" + (i + 1).ToString() + ".jpg";                    string strPath2 = m_imagefilepath + "\\" + (i + 1).ToString() + "s.jpg";                    ls_bp.Save(strPath);                    //m_COTSReportProjFileMgrClr.ReZoom(strPath, strPath2);                    System.IO.File.Delete(strPath);//再将文件删除                }                string str1 = table["str9"].ToString();                MessageBox.Show(str1 + m_dt.Rows.Count.ToString());            }        }        /// <summary>        /// 导出二次放大图像        /// </summary>        /// <param name="str_srcPathName"></param>        /// <param name="str_outPathName"></param>        public void ParticleReZoom(string str_srcPathName, string str_outPathName)        {            //m_COTSReportProjFileMgrClr.ReZoom(str_srcPathName, str_outPathName);        }        private void ToolStripMenuItem3_Click(object sender, EventArgs e)        {            //恢复至初始状态            dgV_ParticlesDevidePage.Rows.Clear();            dgV_ParticlesDevidePage.Columns.Clear();            BindDataGridView();            SetDataGridViewStyle();        }        private void ToolStripMenuItem5_Click(object sender, EventArgs e)        {            /*注意:多数据源情况下,只获取第一个数据源的选择了多行的情况下,只获取最后一个选择行的,没有办法,这是为了符合李阳博士提出的要求*/            //先获取鼠标所选择的行里的颗粒的FieldID和ParticleID            string i_ls_fieldid = "";            string i_ls_particleid = "";            int cou = dgV_ParticlesDevidePage.SelectedRows.Count;            if (cou > 0)            {                DataGridViewRow dgvr = dgV_ParticlesDevidePage.SelectedRows[cou - 1];                Bitmap ls_bp = (Bitmap)dgvr.Cells[2].Value;                List<string> list_str = (List<string>)ls_bp.Tag;                if (list_str != null)                {                    i_ls_fieldid = list_str[0];                    i_ls_particleid = list_str[1];                }            }            ParticleData particleData = new ParticleData(result.FilePath);            Particle particle = particleData.GetParticleByFidAndPid(i_ls_fieldid, i_ls_particleid);            ////然后遍历所有的Field            //Point ls_ots_point = new Point() { X = particle.PosX, Y = particle.PosY };            ////将该坐标转成SEM坐标            //Point ls_sem_point = ChangeOTSToSemCoord(ls_ots_point);            //取得Field的Position,然后执行线程移动SEM到当前Field的位置            if (m_mythread == null)            {                return;            }            if (m_mythread.ThreadState == ThreadState.Running || m_mythread.ThreadState == ThreadState.WaitSleepJoin)            {                return;            }            if (m_mythread.ThreadState == ThreadState.Stopped)            {                m_mythread = new Thread(new ParameterizedThreadStart(Thread_GO));            }            //改为线程调用,先判断线程状态            m_mythread.Start(new Point(particle.SEMPosX, particle.SEMPosY));        }        private void ToolStripMenuItem_selectparticle_Click(object sender, EventArgs e)        {            string path = result.FilePath;            ParticleData fielddata = new ParticleData(result.FilePath);            List<Particle> particles = fielddata.GetParticleAllList();            List<Particle> ls_list_cotsparticleclr = new List<Particle>();            for (int l = 0; l < dgV_ParticlesDevidePage.SelectedRows.Count; l++)            {                //从事先加载的Bitmap对象的Tag中取出List<string>                DataGridViewRow dgvr = dgV_ParticlesDevidePage.SelectedRows[l];                Bitmap ls_bp = (Bitmap)dgvr.Cells[2].Value;                List<string> list_str = (List<string>)ls_bp.Tag;                if (list_str != null)                {                    int i_ls_fieldid = Convert.ToInt32(list_str[0]);                    int i_ls_particleid = Convert.ToInt32(list_str[1]);                    foreach (Particle item in particles)                    {                        if (i_ls_fieldid == item.FieldId && i_ls_particleid == item.ParticleId)                        {                            ls_list_cotsparticleclr.Add(item);                            break;                        }                    }                }            }            m_ReportApp.SetSelectedParticles(ls_list_cotsparticleclr);            string str1 = table["str1"].ToString();            //然后循环得出,list cotsparticleclr列表,返回给框架            //m_sec.SendCall(str1, "", "", ls_list_cotsparticleclr);            string str2 = table["str2"].ToString();            string str3 = table["str3"].ToString();            MessageBox.Show(str2 + ls_list_cotsparticleclr.Count.ToString() + str3);        }        private void ToolStripMenuItem_exportimagefile_Click(object sender, EventArgs e)        {            FolderBrowserDialog fbd = new FolderBrowserDialog();            if (fbd.ShowDialog() == DialogResult.OK)            {                m_imagefilepath = fbd.SelectedPath;                for (int i = 0; i < dgV_ParticlesDevidePage.Rows.Count; i++)                {                    Bitmap ls_bp = new Bitmap(1, 1);                    ls_bp = (Bitmap)dgV_ParticlesDevidePage.Rows[i].Cells[2].Value;                    ls_bp.Save(m_imagefilepath + "\\" + (i + 1).ToString() + ".jpg");                }                string str9 = table["str9"].ToString();                MessageBox.Show(str9 + dgV_ParticlesDevidePage.Rows.Count.ToString());            }        }        private void testToolStripMenuItem_Click(object sender, EventArgs e)        {            ////测试导出指定颗粒的能谱图,测试相关代码            //OTSIncAReportGraph.DParticle ls_dparticle = new OTSIncAReportGraph.DParticle();            //for (int i = 0; i < dgV_ParticlesDevidePage.SelectedRows.Count; i++)            //{            //    //获取选择行颗粒的fieldid,和particleid            //    string str_fieldid = "";            //    string str_particleid = "";            //    string str_stdtypeid = "";            //    DataGridViewRow dgvr = dgV_ParticlesDevidePage.SelectedRows[i];            //    Bitmap ls_bp = (Bitmap)dgvr.Cells[2].Value;            //    List<string> list_str = (List<string>)ls_bp.Tag;            //    if (list_str != null)            //    {            //        str_fieldid = list_str[0];            //        str_particleid = list_str[1];            //        str_stdtypeid = list_str[2];            //    }            //    ls_dparticle.CLRFieldID = Convert.ToInt32(str_fieldid);            //    ls_dparticle.CLRTagID = Convert.ToInt32(str_particleid);            //    ls_dparticle.STDTypeID = Convert.ToInt32(str_stdtypeid);            //}            ////显示xray能谱            //ShowXRay(ls_dparticle);            //Bitmap ls_bpex = new Bitmap(control_XRayTable1.Width, control_XRayTable1.Height);            //control_XRayTable1.DrawToBitmap(ls_bpex, new Rectangle(0, 0, control_XRayTable1.Width, control_XRayTable1.Height));            ////Bitmap ls_bpex = control_XRayTable1.ExportXRayImage();            //ls_bpex.Save("e:\\test222.jpg");        }        /// <summary>        /// 判断条件输入 前<后        /// </summary>        /// <param name="min"></param>        /// <param name="max"></param>        /// <returns></returns>        bool CompareInput(string min, string max)        {            int imax = 0;            int imin = 0;            double dmax = 0;            double dmin = 0;            if (int.TryParse(max, out imax))            {                dmax = (double)imax;            }            else            {                dmax = Convert.ToDouble(max);            }            if (int.TryParse(min, out imin))            {                dmin = (double)imin;            }            else            {                dmin = Convert.ToDouble(min);            }            if (dmin <= dmax)            {                return true;            }            else            {                return false;            }        }        private void btn_Sel_Click(object sender, EventArgs e)        {            condition = "";            if (!string.IsNullOrWhiteSpace(tBx_AreaMin.Text))            {                double dnum = 0;                int inum = 0;                if (double.TryParse(tBx_AreaMin.Text, out dnum) && dnum >= 0)                {                    condition += " and Area" + " > " + tBx_AreaMin.Text;                }                else if (int.TryParse(tBx_AreaMin.Text, out inum) && inum >= 0)                {                    condition += " and Area" + " > " + tBx_AreaMin.Text;                }                else                {                    MessageBox.Show(table["str10"].ToString());                    return;                }            }            if (!string.IsNullOrWhiteSpace(Tbx_AreaMax.Text))            {                double dnum = 0;                int inum = 0;                if (double.TryParse(Tbx_AreaMax.Text, out dnum) && dnum >= 0)                {                    condition += " and Area" + "<" + Tbx_AreaMax.Text;                }                else if (int.TryParse(Tbx_AreaMax.Text, out inum) && inum >= 0)                {                    condition += " and Area" + "<" + Tbx_AreaMax.Text;                }                else                {                    MessageBox.Show(table["str10"].ToString());                    return;                }            }            if (!string.IsNullOrWhiteSpace(tBx_AreaMin.Text) && !string.IsNullOrWhiteSpace(Tbx_AreaMax.Text))            {                if (!CompareInput(tBx_AreaMin.Text, Tbx_AreaMax.Text))                {                    MessageBox.Show(table["str11"].ToString());                    return;                }            }            if (!string.IsNullOrWhiteSpace(tbx_DmaxMin.Text))            {                double dnum = 0;                int inum = 0;                if (double.TryParse(tbx_DmaxMin.Text, out dnum) && dnum >= 0)                {                    condition += " and DMAX" + " > " + tbx_DmaxMin.Text;                }                else if (int.TryParse(tbx_DmaxMin.Text, out inum) && inum >= 0)                {                    condition += " and DMAX" + " > " + tbx_DmaxMin.Text;                }                else                {                    MessageBox.Show(table["str10"].ToString());                    return;                }            }            if (!string.IsNullOrWhiteSpace(tbx_DmaxMax.Text))            {                double dnum = 0;                int inum = 0;                if (double.TryParse(tbx_DmaxMax.Text, out dnum) && dnum > 0)                {                    condition += " and DMAX" + "<" + tbx_DmaxMax.Text;                }                else if (int.TryParse(tbx_DmaxMax.Text, out inum) && inum >= 0)                {                    condition += " and DMAX" + "<" + tbx_DmaxMax.Text;                }                else                {                    MessageBox.Show(table["str10"].ToString());                    return;                }            }            if (!string.IsNullOrWhiteSpace(tB_FieldId.Text))            {                int inum = 0;                if (int.TryParse(tB_FieldId.Text, out inum))                {                    condition += " and FieldId =" + tB_FieldId.Text;                }                else                {                    MessageBox.Show(table["str10"].ToString());                    return;                }            }            if (!string.IsNullOrWhiteSpace(tB_ParticleId.Text))            {                int inum = 0;                if (int.TryParse(tB_ParticleId.Text, out inum))                {                    condition += " and ParticleId =" + tB_ParticleId.Text;                }                else                {                    MessageBox.Show(table["str10"].ToString());                    return;                }            }            if (!string.IsNullOrWhiteSpace(tbx_DmaxMin.Text) && !string.IsNullOrWhiteSpace(tbx_DmaxMax.Text))            {                if (!CompareInput(tbx_DmaxMin.Text, tbx_DmaxMax.Text))                {                    MessageBox.Show(table["str11"].ToString());                    return;                }            }            if (!string.IsNullOrWhiteSpace(tbx_Type.Text))            {                condition += " and TypeName Like \"%" + tbx_Type.Text + "%\" ";            }            if (m_frm_userprogress.IsDisposed)            {                ProgressStart();            }            UpdateTable();            lnkFirst_Click(null, null);            SetDataGridViewStyle();        }        void ProgressStart()        {            #region 加载显示进度条部份            this.Cursor = Cursors.WaitCursor;            m_frm_userprogress = new Frm_UserProgress();            //显示进度条,计算进度条应该显示的位置和宽度            Form ls_main_form = this.ParentForm.ParentForm;//取出父窗体            if (ls_main_form == null)            {                m_frm_userprogress.Visible = false;            }            else            {                m_frm_userprogress.Width = (int)(MyPrimaryScreen.DESKTOP.Width / MyPrimaryScreen.ScaleX * 0.9);                m_frm_userprogress.Location = new Point(ls_main_form.Location.X + 80, ls_main_form.Location.Y + (int)(MyPrimaryScreen.DESKTOP.Height / MyPrimaryScreen.ScaleX) / 2);                m_frm_userprogress.Show();                m_frm_userprogress.SetProgressValueAndText(0, "Loading data of particles...");            }            #endregion        }        private void cbB_order_SelectedIndexChanged(object sender, EventArgs e)        {            //int ordernum = cbB_order.SelectedIndex;            //if (ordernum == 0)            //{            //    OrderFunction = "fieldid,particleid";            //}            //else if (ordernum == 1)            //{            //    OrderFunction = "TypeName";            //}            //else if (ordernum == 2)            //{            //    OrderFunction = "DMAX";            //}            //else if (ordernum == 3)            //{            //    OrderFunction = "DMAX desc";            //}            //else if (ordernum == 4)            //{            //    OrderFunction = "Area";            //}            //else if (ordernum == 5)            //{            //    OrderFunction = "Area desc";            //}            lnkFirst_Click(null, null);            SetDataGridViewStyle();        }        /// <summary>        /// 页面控件呈现        /// </summary>        private void DrawControl(bool callEvent)        {            BindDataGridView();            lblTotalCount.Text = RecordCount.ToString();            lblPageCount.Text = PageCount.ToString();            txtPageNum.Text = PageIndex.ToString();            SetFormCtrEnabled();            if (PageCount == 0 || PageCount == 1)//有且仅有一页            {                lnkFirst.Enabled = false;                lnkPrev.Enabled = false;                lnkNext.Enabled = false;                lnkLast.Enabled = false;                btnGo.Enabled = false;            }            else if (PageIndex == 1)//第一页            {                lnkFirst.Enabled = false;                lnkPrev.Enabled = false;            }            else if (PageIndex == PageCount)//最后一页            {                lnkNext.Enabled = false;                lnkLast.Enabled = false;            }        }        private void SetFormCtrEnabled()        {            lnkFirst.Enabled = true;            lnkPrev.Enabled = true;            lnkNext.Enabled = true;            lnkLast.Enabled = true;            btnGo.Enabled = true;        }        /// <summary>        /// 分页属性改变了。        /// </summary>        private void txtPageSize_TextChanged(object sender, EventArgs e)        {            int num = 0;            if (int.TryParse(txtPageNum.Text.Trim(), out num) && num > 0)            {            }            else { txtPageNum.Text = "1"; }        }        private void lnkFirst_Click(object sender, EventArgs e)        {            PageIndex = 1;            DrawControl(true);        }        private void lnkPrev_Click(object sender, EventArgs e)        {            PageIndex = Math.Max(1, PageIndex - 1);            DrawControl(true);        }        private void lnkNext_Click(object sender, EventArgs e)        {            PageIndex = Math.Min(PageCount, PageIndex + 1);            DrawControl(true);        }        private void lnkLast_Click(object sender, EventArgs e)        {            PageIndex = PageCount;            DrawControl(true);        }        /// <summary>        /// 跳转        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnGo_Click(object sender, EventArgs e)        {            int num = 0;            if (int.TryParse(txtPageNum.Text.Trim(), out num) && num > 0)            {                if (num > PageCount)                {                    num = PageCount;                    txtPageNum.Text = PageCount.ToString();                }                PageIndex = num;                DrawControl(true);            }        }        private void cbB_PageSize_SelectedIndexChanged(object sender, EventArgs e)        {            DisplayData();        }        /// <summary>        /// 在帧图上标记颗粒的位置矩形,并保存到FIELD_FILES_MARK文件夹中        /// </summary>        public void SaveMarkParticleRectangleOnFieldFile(string str_resultPath, DataTable dataTable, out List<string> vs, out DataTable dt_FIeld)        {            Init();            List<string> maxlength = new List<string>();            for (int i = 0; i < dataTable.Rows.Count; i++)            {                if (dataTable.Rows[i]["TypeName"].ToString() != "Not Identified")                {                    if (maxlength.Count < 10)                    {                        maxlength.Add(dataTable.Rows[i]["Fieldid"].ToString());                    }                    else                    {                        break;                    }                }            }            List<string> max_list = maxlength.Distinct().ToList();            string str_path_FIELD_FILES = str_resultPath + "\\FIELD_FILES\\";            string str_path_FIELD_FILES_MARK = str_resultPath + "\\FIELD_FILES_MARK\\";            int intQuantity = 0;            //List<string> vs = new List<string>();            dt_FIeld = new DataTable();            vs = new List<string>();            ////判断是否已经有导出过的标记帧图文件夹,如果已经存在,则直接返回不输出,先不加            DirectoryInfo theFolder_FieldMark = new DirectoryInfo(str_path_FIELD_FILES_MARK);            if (!theFolder_FieldMark.Exists)            {                //创建                theFolder_FieldMark.Create();            }            else            {                theFolder_FieldMark.Delete(true);                //创建                theFolder_FieldMark.Create();                //已经存在的话,直接返回                //return;            }            //查找该field下对应所有的颗粒            DataTable dt_AllParticle = fieldData.GetAllParticle_DataTable();            DirectoryInfo theFolder = new DirectoryInfo(str_path_FIELD_FILES);            if (theFolder.Exists)            {                DataTable dt = new DataTable();                dt.Columns.Add("fieldid");                dt.Columns.Add("id");                dt.Columns.Add("fieldName");                dt.Columns.Add("cunt", typeof(int));                dt.Columns.Add("fieldFullName");                for (int i = 0; i < max_list.Count; i++)                {                    foreach (FileInfo nextifile in theFolder.GetFiles())                    {                        if (nextifile.Name.Contains(".bmp") == true || nextifile.Name.Contains(".BMP") == true)                        {                            //确认对应的帧图名                            string str_fieldid = Path.GetFileNameWithoutExtension(nextifile.Name);                            str_fieldid = str_fieldid.Substring(5, str_fieldid.Length - 5);//减去field字符长度                            bool bl = false;                            if (str_fieldid == max_list[i].ToString())                            {                                bl = true;                            }                            if (bl)                            {                                DataRow dr = dt.NewRow();                                dr["fieldid"] = " fieldid = " + str_fieldid;                                dr["cunt"] = dataTable.Select(" fieldid = " + str_fieldid).Count();                                dr["fieldName"] = nextifile.Name;                                dr["fieldFullName"] = nextifile.FullName;                                dr["id"] = str_fieldid;                                dt.Rows.Add(dr);                            }                        }                    }                }                //DataView dv = dt.DefaultView;                //dv.Sort = "cunt DESC";                dt_FIeld = dt.Copy();                for (int i = 0; i < dt_FIeld.Rows.Count; i++)                {                    if (dataTable.Select(dt_FIeld.Rows[i]["fieldid"].ToString()).Count() > 0)                    {                        vs.Add(dt_FIeld.Rows[i]["id"].ToString());                        Image img = Image.FromFile(dt_FIeld.Rows[i]["fieldFullName"].ToString());                        //img.Save(@"D:\1.bmp");                        Bitmap ls_fieldbp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);                        using (Graphics g = Graphics.FromImage(ls_fieldbp))                        {                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;                            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;                            g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));                        }                        //ls_fieldbp.Save(@"D:\1.bmp");                        img.Dispose();                        img = null;                        //循环将颗粒,进行标记到bitmap图上                        DataRow[] drlist = dt_AllParticle.Select(dt_FIeld.Rows[i]["fieldid"].ToString());                        if (drlist.Count() > 0)                            intQuantity = intQuantity + 1;                        for (int i_row = 0; i_row < drlist.Count(); i_row++)                        {                            //string str_fieldid = drlist[i_row]["fieldid"].ToString();                            string str_particleid = drlist[i_row]["particleid"].ToString();                            string str_stdtypeid = drlist[i_row]["typeid"].ToString();                            string str_offset_rect_X = drlist[i_row]["RectLeft"].ToString();                            string str_offset_rect_Y = drlist[i_row]["RectTop"].ToString();                            string str_offset_rect_Width = drlist[i_row]["RectWidth"].ToString();                            string str_offset_rect_Height = drlist[i_row]["RectHeight"].ToString();                            //确定需要标记颗粒的定位                            Rectangle offset_rect = new Rectangle(Convert.ToInt32(str_offset_rect_X), Convert.ToInt32(str_offset_rect_Y),                    Convert.ToInt32(str_offset_rect_Width), Convert.ToInt32(str_offset_rect_Height));                            //向帧图进行标记颗粒位置                            Graphics g = Graphics.FromImage(ls_fieldbp);                            g.DrawRectangle(new Pen(Color.Aquamarine), offset_rect);                            //判断是否超出了图像外面,是的话,让文字在左侧显示,默认在右侧显示                            int ls_offsetx = offset_rect.X + offset_rect.Width;                            if (ls_offsetx > ls_fieldbp.Width - 10)                            {                                ls_offsetx = offset_rect.X - 10;                            }                            g.DrawString(dt_FIeld.Rows[i]["id"].ToString() + "" + str_particleid.ToString(),                                new Font("黑体", 8), new SolidBrush(Color.Aqua), new PointF(ls_offsetx, offset_rect.Y));                            //保存带有标记的帧图                            ls_fieldbp.Save(str_path_FIELD_FILES_MARK + dt_FIeld.Rows[i]["id"].ToString() + ".bmp");                            //ls_fieldbp.Dispose();                        }                    }                }            }            //            GC.Collect();            GC.WaitForPendingFinalizers();        }        private void testToolStripMenuItem1_Click(object sender, EventArgs e)        {            //SaveMarkParticleRectangleOnFieldFile();            MessageBox.Show("Export completed!");        }        private void EXCELToolStripMenuItem_Click(object sender, EventArgs e)        {            OTSIncAReportApp._1_UI.Control_Grids.SpectrumExportConfirmation sfd = new OTSIncAReportApp._1_UI.Control_Grids.SpectrumExportConfirmation();            if (sfd.ShowDialog() == DialogResult.OK)            {                Cursor = Cursors.WaitCursor;                //IWorkbook workbook = new HSSFWorkbook();   //用于创建.xls  office2003开始以前的                IWorkbook workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();        //用于创建.xlsx office2007开始以后的                ISheet sheet;                //创建Excel文件                FileStream fs = File.Create(sfd.FileName);                fs.Close();                sheet = workbook.CreateSheet("Particles");//创建工作表                //创建表格边框样式风格                ICellStyle cellStyle = workbook.CreateCellStyle();                cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;                cellStyle.VerticalAlignment = VerticalAlignment.Center;                //设置上4边                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;                cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;                cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;                cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;                //设置字符大小和颜色                IFont font = workbook.CreateFont();                font.FontName = "黑体";                font.FontHeightInPoints = 10;                cellStyle.SetFont(font);                //设置颗粒名列宽                sheet.SetColumnWidth(1, 30 * 256);//夹杂物名列宽                sheet.SetColumnWidth(2, 7 * 256);//图像列宽                IRow row;                ICell cell;                //插入表头                row = sheet.CreateRow(1);//从第15行添加一行                row.Height = 30 * 20;                for (int i_cell = 0; i_cell < dgV_ParticlesDevidePage.Columns.Count; i_cell++)                {                    cell = row.CreateCell(i_cell);                    cell.CellStyle = cellStyle;                    cell.SetCellValue(dgV_ParticlesDevidePage.Columns[i_cell].Name);                }                //插入表内容                for (int i_row = 0; i_row < dgV_ParticlesDevidePage.Rows.Count; i_row++)                {                    row = sheet.CreateRow(2 + i_row);                    row.Height = 45 * 20;                    for (int i_cell = 0; i_cell < dgV_ParticlesDevidePage.Columns.Count; i_cell++)                    {                        cell = row.CreateCell(i_cell);                        cell.CellStyle = cellStyle;                        if (dgV_ParticlesDevidePage[i_cell, i_row].Value == null)                            continue;                        if (i_cell == 2)                        {                            //颗粒图像列                            Bitmap bp = (Bitmap)dgV_ParticlesDevidePage.Rows[i_row].Cells[2].Value;                            byte[] bytes = ImageConvertToBytes(bp);                            //第二步,将图片添加到workbook中,指定图片的格式,返回图片所在workbook->paicture数组中的索引的地址,从1开始                            int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);                            //第三步,在sheet中创建画布                            IDrawing patriarch = sheet.CreateDrawingPatriarch();                            //第四步,设置锚点,(在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格行数,列数,终止单元格行数,列数)                            IClientAnchor anchor = patriarch.CreateAnchor(1, 1, 2, 2, i_cell, i_row + 2, i_cell + 1, i_row + 3);//终止比开始位置大1,会自动缩放到一个单元格内的                            //第五步,创建图片                            IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);                            //图像效果不好,自己另外导出吧,这里对该列宽进行了设置0                        }                        else                        {                            //非图像列                            double dbl = 0;                            if (double.TryParse(dgV_ParticlesDevidePage[i_cell, i_row].Value.ToString(), out dbl))                            {                                cell.SetCellValue(dbl);                            }                            else                            {                                cell.SetCellValue(dgV_ParticlesDevidePage[i_cell, i_row].Value.ToString());                            }                        }                    }                }                ISheet sheet2;                sheet2 = workbook.CreateSheet("Peak spectrum Data");//创建工作表                //插入表头                row = sheet2.CreateRow(1);                row.Height = 30 * 20;                cell = row.CreateCell(0);                cell.CellStyle = cellStyle;                cell.SetCellValue("rowid");                for (int i_cell = 1; i_cell < 2001; i_cell++)                {                    cell = row.CreateCell(i_cell);                    cell.CellStyle = cellStyle;                    if (i_cell == 1)                    {                        cell.SetCellValue("PeakSpectrumData");                    }                }                sheet2.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(1, 1, 1, 2000));                for (int j = 0; j < particles.Rows.Count; j++)                {                    row = sheet2.CreateRow(2 + j);                    cell = row.CreateCell(0);                    cell.CellStyle = cellStyle;                    cell.SetCellValue(j + 1);                    var tmpPart = Particledata.GetParticleXrayDataByFidAndPid(particles.Rows[j]["fieldid"].ToString(), particles.Rows[j]["particleid"].ToString());                    if (tmpPart != null)                    {                        if (tmpPart.XrayId > -1)                        {                            uint[] Analysis_xray = new uint[2000];                            for (int i = 0; i < 2000; i++)                            {                                Analysis_xray[i] = BitConverter.ToUInt32(tmpPart.XRayData, i * 4);                                cell = row.CreateCell(i + 1);                                cell.CellStyle = cellStyle;                                cell.SetCellValue(Analysis_xray[i]);                            }                        }                    }                }                if (sfd.SpectrumConfirmation)                {                    ISheet sheet3;                    sheet3 = workbook.CreateSheet("Peak spectrum");                    sheet3.SetColumnWidth(1, 200 * 256);//图像列宽                                                        //插入表头                    row = sheet3.CreateRow(1);                    row.Height = 30 * 20;                    cell = row.CreateCell(0);                    cell.CellStyle = cellStyle;                    cell.SetCellValue("rowid");                    cell = row.CreateCell(1);                    cell.CellStyle = cellStyle;                    cell.SetCellValue("PeakSpectrum");                    IDrawing drawing;                    IClientAnchor anchor3;                    for (int j = 0; j < particles.Rows.Count; j++)                    {                        row = sheet3.CreateRow(j + 2);                        row.Height = 120 * 20;                        cell = row.CreateCell(0);                        cell.CellStyle = cellStyle;                        cell.SetCellValue(j + 1);                        row.CreateCell(1);                        row.CreateCell(2);                        row.CreateCell(3);                        drawing = sheet3.CreateDrawingPatriarch();                        //锚点                        anchor3 = drawing.CreateAnchor(0, 0, 0, 0, 1, j + 2, 2, j + 3);//XSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2);参数说明:dx1 dy1 起始单元格中的x,y坐标.dx2 dy2 结束单元格中的x,y坐标col1, row1 指定起始的单元格,下标从0开始col2, row2 指定结束的单元格,下标从0开始                        CreateChart(drawing, sheet2, anchor3, j + 2);                    }                }                //完成后,对Excel进行保存                FileStream file = new FileStream(sfd.FileName, FileMode.Create);                workbook.Write(file);                file.Close();                MessageBox.Show("Export complete!");                //导出完成后,打开Excel文件                if (File.Exists(sfd.FileName))                {                    //打开刚才导出的文件                    System.Diagnostics.Process.Start(sfd.FileName);                }                Cursor = Cursors.Default ;            }        }        void CreateChart(IDrawing drawing, ISheet sheet, IClientAnchor anchor, int rowid)        {            var chart = drawing.CreateChart(anchor) as XSSFChart;            //图表            var data = chart.ChartDataFactory.CreateLineChartData<double, double>(); //折线图            IChartAxis bottomAxis = chart.ChartAxisFactory.CreateCategoryAxis(AxisPosition.Bottom);            IValueAxis leftAxis = chart.ChartAxisFactory.CreateValueAxis(AxisPosition.Left);            leftAxis.Crosses = AxisCrosses.AutoZero;            leftAxis.IsVisible = true;            bottomAxis.IsVisible = true;            //数据源            IChartDataSource<double> ys = DataSources.FromNumericCellRange(sheet, new CellRangeAddress(rowid, rowid, 1, 2001));            Double[] doubles = new Double[2000];            for (int i = 0; i < 2000; i++)            {                doubles[i] = i;            }            IChartDataSource<double> xs = DataSources.FromArray(doubles);            //数据系列            var s1 = data.AddSeries(xs, ys);            // 开始绘制折线图            chart.Plot(data, bottomAxis, leftAxis);        }        /// <summary>        /// 将image转成bytes        /// </summary>        /// <param name="in_img"></param>        /// <returns></returns>        public byte[] ImageConvertToBytes(System.Drawing.Image in_img)        {            MemoryStream ms = new MemoryStream();            in_img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);            return ms.ToArray();        }        public bool CheckParamExist<T>(T Param)        {            if (Param == null)            {                return false;            }            else            {                return true;            }        }        private void ToolStripMenuItem_Delete_Particle_Click(object sender, EventArgs e)        {            string path = result.FilePath;            ParticleData fielddata = new ParticleData(result.FilePath);            List<Particle> particles = fielddata.GetParticleAllList();                      DialogResult dr = MessageBox.Show("Remove all these particles permanently?", "Tips", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);            if (dr == DialogResult.OK)            {                for (int ii = 0; ii < dgV_ParticlesDevidePage.SelectedRows.Count; ii++)                {                    //从事先加载的Bitmap对象的Tag中取出List<string>                    DataGridViewRow dgvr = dgV_ParticlesDevidePage.SelectedRows[ii];                    Bitmap ls_bp = (Bitmap)dgvr.Cells[2].Value;                    List<string> list_str = (List<string>)ls_bp.Tag;                    if (list_str != null)                    {                        int i_ls_fieldid = Convert.ToInt32(list_str[0]);                        int i_ls_particleid = Convert.ToInt32(list_str[1]);                        foreach (Particle item in particles)                        {                            if (i_ls_fieldid == item.FieldId && i_ls_particleid == item.ParticleId)                            {                                if (DeleteParticlesFromLibrary(item.ParticleId, item.FieldId))                                {                                                                      for (int i = 0; i < particlesAll.Rows.Count; i++)                                    {                                        if (particlesAll.Rows[i]["Fieldid"].ToString() == item.FieldId.ToString() && particlesAll.Rows[i]["Particleid"].ToString() == item.ParticleId.ToString())                                        {                                            particlesAll.Rows.RemoveAt(i);                                        }                                    }                                                                  }                                else                                {                                    MessageBox.Show("Delete failed");                                }                                break;                            }                        }                    }                }                DisplayData();            }        }        private bool DeleteParticlesFromLibrary(int in_clr_tagid, int in_clr_fieldid)        {            bool DoesItExist = false;            for (int i = 1; i < 201; i++)            {                if (System.IO.Directory.Exists(resultFile.FilePath + "\\FIELD_FILES\\Backups" + i.ToString()))                {                    DoesItExist = true;                    break;                }            }            if (!DoesItExist)            {                //备份数据库                BackupDatabase();            }            DoesItExist = false;            //防止为空校验判断            if (resultFile.List_OTSField == null)                return false;            Particle particle = resultFile.List_OTSField.Find(x => x.FieldID == in_clr_fieldid).ParticleList.Find(x => x.ParticleId == in_clr_tagid);            if (new ParticleData(resultFile.FilePath).DeleteFromData(Convert.ToString(particle.FieldId), Convert.ToString(particle.XrayId)))            {                return true;            }            else            {                return false;            }        }        private bool BackupDatabase()        {            //创建备份数据库文件夹            string sourcePath = resultFile.FilePath + "\\FIELD_FILES\\Inclusion.db";//源文件路径            string sourceName = "Inclusion.db";//源文件名称            string folderPath = resultFile.FilePath + "\\FIELD_FILES\\Backups";//目标文件夹            string Fields = "";            for (int i = 1; i < 201; i++)            {                if (System.IO.Directory.Exists(folderPath + i.ToString()))                {                    Fields = folderPath + i.ToString();                    continue;                }                else                {                    System.IO.Directory.CreateDirectory(folderPath + i.ToString());                    Fields = folderPath + i.ToString();                    break;                }            }            if (Fields == "")            {                return false;            }            //复制数据库文件            string targetPath = Path.Combine(Fields, sourceName);            FileInfo file = new FileInfo(sourcePath);            if (file.Exists)            {                file.CopyTo(targetPath, true);            }            return true;        }        private void DisplayData()        {            if (cbB_PageSize.SelectedItem.ToString() == "All")            {                pageSize = -1;            }            else            {                pageSize = int.Parse(cbB_PageSize.SelectedItem.ToString());            }            lnkFirst_Click(null, null);            SetDataGridViewStyle();        }        private void btn_ReMeasure_Click(object sender, EventArgs e)        {            //二次测量参数页面            frmReMeasure frmReMeasure = new frmReMeasure(m_OTSIncAReportGridsFun, m_ReportApp.GetSelectedParticles(), resultFile);            frmReMeasure.TopMost = true;//设置置顶            frmReMeasure.ShowDialog();        }        string ChangeHardnessColor(string Hardness)        {            string str = System.Text.RegularExpressions.Regex.Replace(Hardness, @"[^\d.\d]", "");            double hd;            if (double.TryParse(str, out hd))            {                if (hd >= 1000)                {                    return "#FF0000";                }                else return "";            }            else                return "";        }        /// <summary>        ///         /// </summary>        /// <param name="str_resultPath"></param>        /// <param name="dataTable"></param>        /// <param name="vs"></param>        /// <param name="dt_FIeld"></param>        public void Out_MarkParticleRectangleOnFieldFile(string str_resultPath, DataTable dataTable, out List<string> vs, out DataTable dt_FIeld)        {            Init();            List<string> maxlength = new List<string>();            for (int i = 0; i < dataTable.Rows.Count; i++)            {                if (dataTable.Rows[i]["TypeName"].ToString() != "Not Identified")                {                    if (maxlength.Count < 10)                    {                        maxlength.Add(dataTable.Rows[i]["Fieldid"].ToString());                    }                    else                    {                        break;                    }                }            }            List<string> max_list = maxlength.Distinct().ToList();            string str_path_FIELD_FILES = str_resultPath + "\\FIELD_FILES\\";            int intQuantity = 0;            dt_FIeld = new DataTable();            vs = new List<string>();            //查找该field下对应所有的颗粒            DataTable dt_AllParticle = fieldData.GetAllParticle_DataTable();            DirectoryInfo theFolder = new DirectoryInfo(str_path_FIELD_FILES);            if (theFolder.Exists)            {                DataTable dt = new DataTable();                dt.Columns.Add("fieldid");                dt.Columns.Add("id");                dt.Columns.Add("fieldName");                dt.Columns.Add("cunt", typeof(int));                dt.Columns.Add("fieldFullName");                for (int i = 0; i < max_list.Count; i++)                {                    foreach (FileInfo nextifile in theFolder.GetFiles())                    {                        if (nextifile.Name.Contains(".bmp") == true || nextifile.Name.Contains(".BMP") == true)                        {                            //确认对应的帧图名                            string str_fieldid = Path.GetFileNameWithoutExtension(nextifile.Name);                            str_fieldid = str_fieldid.Substring(5, str_fieldid.Length - 5);//减去field字符长度                            bool bl = false;                            if (str_fieldid == max_list[i].ToString())                            {                                bl = true;                            }                            if (bl)                            {                                DataRow dr = dt.NewRow();                                dr["fieldid"] = " fieldid = " + str_fieldid;                                dr["cunt"] = dataTable.Select(" fieldid = " + str_fieldid).Count();                                dr["fieldName"] = nextifile.Name;                                dr["fieldFullName"] = nextifile.FullName;                                dr["id"] = str_fieldid;                                dt.Rows.Add(dr);                            }                        }                    }                }                dt_FIeld = dt.Copy();                dt_FIeld.Columns.Add("Field_pic", typeof(Bitmap));                for (int i = 0; i < dt_FIeld.Rows.Count; i++)                {                    if (dataTable.Select(dt_FIeld.Rows[i]["fieldid"].ToString()).Count() > 0)                    {                        vs.Add(dt_FIeld.Rows[i]["id"].ToString());                        Image img = Image.FromFile(dt_FIeld.Rows[i]["fieldFullName"].ToString());                        //img.Save(@"D:\1.bmp");                        Bitmap ls_fieldbp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);                        using (Graphics g = Graphics.FromImage(ls_fieldbp))                        {                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;                            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;                            g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));                        }                        //ls_fieldbp.Save(@"D:\1.bmp");                        img.Dispose();                        img = null;                        //循环将颗粒,进行标记到bitmap图上                        DataRow[] drlist = dt_AllParticle.Select(dt_FIeld.Rows[i]["fieldid"].ToString());                        if (drlist.Count() > 0)                            intQuantity = intQuantity + 1;                        for (int i_row = 0; i_row < drlist.Count(); i_row++)                        {                            //string str_fieldid = drlist[i_row]["fieldid"].ToString();                            string str_particleid = drlist[i_row]["particleid"].ToString();                            string str_stdtypeid = drlist[i_row]["typeid"].ToString();                            string str_offset_rect_X = drlist[i_row]["RectLeft"].ToString();                            string str_offset_rect_Y = drlist[i_row]["RectTop"].ToString();                            string str_offset_rect_Width = drlist[i_row]["RectWidth"].ToString();                            string str_offset_rect_Height = drlist[i_row]["RectHeight"].ToString();                            //确定需要标记颗粒的定位                            Rectangle offset_rect = new Rectangle(Convert.ToInt32(str_offset_rect_X), Convert.ToInt32(str_offset_rect_Y),                    Convert.ToInt32(str_offset_rect_Width), Convert.ToInt32(str_offset_rect_Height));                            //向帧图进行标记颗粒位置                            Graphics g = Graphics.FromImage(ls_fieldbp);                            g.DrawRectangle(new Pen(Color.Aquamarine), offset_rect);                            //判断是否超出了图像外面,是的话,让文字在左侧显示,默认在右侧显示                            int ls_offsetx = offset_rect.X + offset_rect.Width;                            if (ls_offsetx > ls_fieldbp.Width - 10)                            {                                ls_offsetx = offset_rect.X - 10;                            }                            g.DrawString(dt_FIeld.Rows[i]["id"].ToString() + "" + str_particleid.ToString(),                                new Font("黑体", 8), new SolidBrush(Color.Aqua), new PointF(ls_offsetx, offset_rect.Y));                            dt_FIeld.Rows[i]["Field_pic"] = ls_fieldbp;                            //保存带有标记的帧图                            //ls_fieldbp.Save(str_path_FIELD_FILES_MARK + dt_FIeld.Rows[i]["id"].ToString() + ".bmp");                            //ls_fieldbp.Dispose();                        }                    }                }            }            //            GC.Collect();            GC.WaitForPendingFinalizers();        }        private void ImportSTDDb_Click(object sender, EventArgs e)        {            Dictionary<string, object> sampleMembers = ((Dictionary<string, object>)((Dictionary<string, object>)resultFile.ResultInfo["Sample"])["Members"]);            string STDName = ((Dictionary<string, object>)sampleMembers["MsrParams"])["STDName"].ToString();            string ResultDbPath = resultFile.FilePath + "\\FIELD_FILES\\Inclusion.db";            if (STDName.ToLower().Split('.')[0] == "nostddb")            {                OpenFileDialog openFileDialog = new OpenFileDialog();                openFileDialog.Filter = "(*.db)|*.db";                openFileDialog.RestoreDirectory = true;                openFileDialog.FilterIndex = 1;                openFileDialog.Title = "Please choose a STD to add the rule!";                if (openFileDialog.ShowDialog() == DialogResult.OK)                {                    try                    {                        string arguments = openFileDialog.FileName;                        var SelectRows= dgV_ParticlesDevidePage.SelectedRows;                        DataGridViewRow dgvr = SelectRows[0];                        Bitmap ls_bp = (Bitmap)dgvr.Cells[2].Value;                        List<string> list_str = (List<string>)ls_bp.Tag;                        arguments += " " + ResultDbPath + " " + list_str[0].ToString() + " " + list_str[1].ToString() + " " + list_str[3].ToString();                        System.Diagnostics.Process p = System.Diagnostics.Process.Start(".\\OTSPartA_STDEditor.exe", arguments);                        p.WaitForExit();                    }                    catch (Exception ex)                    {                        log.Error("OTSPartA_STDEditor:" + ex.ToString());                    }                }            }            else            {                string arguments = ".\\Config\\SysData\\" + STDName.Split('.')[0] + ".db";                var selectRow = dgV_ParticlesDevidePage.SelectedRows[0];                Bitmap ls_bp = (Bitmap)selectRow.Cells[2].Value;                List<string> list_str = (List<string>)ls_bp.Tag;                arguments += " " + ResultDbPath + " " + list_str[0].ToString() + " " + list_str[1].ToString() + " " + list_str[3].ToString();                System.Diagnostics.Process p = System.Diagnostics.Process.Start(".\\OTSPartA_STDEditor.exe", arguments);                p.WaitForExit();            }        }        private void dgV_ParticlesDevidePage_MouseDown(object sender, MouseEventArgs e)        {            var SelectRows = dgV_ParticlesDevidePage.SelectedRows;            int sel = m_ReportApp.m_conditionChoose.m_conditionData.GetComboDownListIndexByItemName(OTSIncAReportApp.OTSSampleReportInfo.OTS_REPORT_PROP_GRID_ITEMS.PARTICE_LIST);            {                if (sel != (int)SelItem.MergeParticles)                {                    if (SelectRows != null && SelectRows.Count == 1)                    {                        DataGridViewRow dgvr = SelectRows[0];                        Bitmap ls_bp = (Bitmap)dgvr.Cells[2].Value;                        List<string> list_str = (List<string>)ls_bp.Tag;                        contextMenuStrip1.Items[10].Visible = true;                    }                    else                    {                        contextMenuStrip1.Items[10].Visible = false;                    }                }                else                {                    contextMenuStrip1.Items[10].Visible = false;                }            }        }    }}
 |