using iTextSharp.text.pdf; using Lskj.Business; using Lskj.Business.Impl; using Lskj.Control; using Lskj.Control.BrowserSetting; using Lskj.Control.Model; using Lskj.Core; using Lskj.Model; using Lskj.Util; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace Lskj.EmbeCad { public partial class FrmMain : BaseForm { /// /// 枚举 /// typeOpenDic = new Dictionary(); #endregion #region 共有变量 public bool isInit = true; public DynamicPubInvokeExeModel SysModel; public ModuleModel Model; public Process proApp; public IntPtr intPtr = IntPtr.Zero; public ExeType exeType = ExeType.None; public string url = string.Empty; public string mainSql = string.Empty; public string name = string.Empty; public string idValue = string.Empty; public bool isAddSign = false; public List filePaths = new List(); public string fileSavePath; public string fileCopyPath; public string scriptPath; public DateTime downFileTime; /// /// 外部exe进程 /// public Dictionary loadExeProcess = new Dictionary(); #endregion public FrmMain() { InitializeComponent(); this.splitMainContainer.SplitterMoved += OnSplitterPositionChanged; this.pl_Main.SizeChanged += OnSizeChanged; } #region 窗口初始化 /// /// 说明:窗口初始化 /// 创建人:王一帆 /// 创建日期: /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The instance containing the event data. protected void OnLoad(object sender, EventArgs e) { try { InitSplitPosition(); InitGridControl(); this.frmWebBrowser.FrmLoad(""); } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } /// /// 说明:右键菜单执行后刷新数据,刷新规则按照上一次查询条件刷新 /// 创建人:王一帆 /// 创建日期:2017-11-02 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected void OnGridViewRightCallBack(object sender, EventArgs e) { try { int oldRowHandle = fileGrid.GridView.FocusedRowHandle; if (!(fileGrid is TreeGridControlEx) && oldRowHandle < 0) return; DataTable dt = this.fileGrid.GridView.GetGridViewFilteredAndSortedDataToDataTable(); if (fileGrid is TreeGridControlEx) dt = (fileGrid as TreeGridControlEx).GetGridViewDataSource(); if (dt == null || dt.Rows.Count == 0) return; //DataRow SelectTheLine = fileGrid is TreeGridControlEx ? (fileGrid as TreeGridControlEx).GetViewFocusedDataRow() : dt.Rows[oldRowHandle]; DataTable dataTable = MainImpl.GetDataTableResult(mainSql); this.fileGrid.gridControl.DataSource = dataTable; this.fileGrid.GridView.FocusedRowHandle = oldRowHandle; } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } /// /// 初始化分割条位置 /// private void InitSplitPosition() { string spliterPosition = IniHelper.Read(string.Format("EmbeCadSpliterPositionMain_{0}", this.SysModel.ModuleCode)); if (!string.IsNullOrEmpty(spliterPosition)) this.splitMainContainer.SplitterDistance = Convert.ToInt32(spliterPosition); } /// /// 初始主表 /// private void InitGridControl() { DataRow modelRow = MainImpl.GetSystemdllTab(this.SysModel.ModuleCode);//获取单个模块信息 if (modelRow == null) { MessageUtil.Show("模块编号[" + this.SysModel.ModuleCode + "],配置错误!\r\n该模块信息未找到!"); return; } this.Model = new ModuleModel(modelRow);// 系统模块实体对象 DataTable _gridColumns = BaseModuleImpl.GetBaseGridColumns(this.SysModel.ModuleCode); this.fileGrid.SetReadOnlyColumns(_gridColumns, GridCustomColumnStruct.BaseCadGridView + this.Model.FormKey); this.mainSql = string.IsNullOrWhiteSpace(SysModel.ControlSql) ? Model.MenuSql : ReplaceHelper.ReplaceRowParam(MainImpl.GetDataRowResult(SysModel.ControlSql), Model.MenuSql); DataTable dataTable = MainImpl.GetDataTableResult(mainSql); this.fileGrid.gridControl.DataSource = dataTable; this.fileGrid.GridView.BestFitColumns(); this.fileGrid.GridView.DoubleClick += OnDoubleClick; DataTable rightMenuTab = BaseModuleImpl.GetBaseGridRightMenus(this.Model.ModeCode); this.fileGrid.SetGridRightMenus(rightMenuTab, this.SysModel, OnGridViewRightCallBack); } /// /// 返回句柄操作 /// public IntPtr OpenCadExe(string filePath, string downUrl) { exeType = ExeType.None; if (Path.GetExtension(filePath).Equals(".doc", StringComparison.CurrentCultureIgnoreCase) || Path.GetExtension(filePath).Equals(".docx", StringComparison.CurrentCultureIgnoreCase)) { exeType = ExeType.Word; } else if (Path.GetExtension(filePath).Equals(".dwg", StringComparison.CurrentCultureIgnoreCase)) { exeType = ExeType.Cad; } else if (Path.GetExtension(filePath).Equals(".xls", StringComparison.CurrentCultureIgnoreCase) || Path.GetExtension(filePath).Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase)) { exeType = ExeType.Excel; } else if (Path.GetExtension(filePath).Equals(".ppt", StringComparison.CurrentCultureIgnoreCase) || Path.GetExtension(filePath).Equals(".pptx", StringComparison.CurrentCultureIgnoreCase)) { exeType = ExeType.PPT; } else if (Path.GetExtension(filePath).Equals(".pdf", StringComparison.CurrentCultureIgnoreCase)) { exeType = ExeType.PDF; } else if (Path.GetExtension(filePath).Equals(".png", StringComparison.CurrentCultureIgnoreCase) || Path.GetExtension(filePath).Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || Path.GetExtension(filePath).Equals(".jpeg", StringComparison.CurrentCultureIgnoreCase)) { exeType = ExeType.Pic; } else if (Path.GetExtension(filePath).Equals(".txt", StringComparison.CurrentCultureIgnoreCase)) { exeType = ExeType.Txt; } else if (Path.GetExtension(filePath).Equals(".pcbdoc", StringComparison.CurrentCultureIgnoreCase)) { //exeType = ExeType.PcbDoc; } if (exeType == ExeType.None && (this.fileGrid.gridControl.DataSource as DataTable).Columns.Contains("IsBrowser") && (this.fileGrid.GridView.GetFocusedDataRow()["IsBrowser"] + "").Equals("1")) { exeType = ExeType.WebPage; } try { if (exeType == ExeType.None) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("不支持的文件格式"); })); } return IntPtr.Zero; } if (exeType != ExeType.PDF && exeType != ExeType.Pic && exeType != ExeType.Txt && exeType != ExeType.Word && exeType != ExeType.Excel && exeType != ExeType.PPT && exeType != ExeType.WebPage) { if (!typeOpenDic.ContainsKey(exeType)) { StringBuilder stringBuilder = new StringBuilder(1024); HandleHelper.FindExecutable(filePath, null, stringBuilder); if (!string.IsNullOrEmpty(stringBuilder + "")) { typeOpenDic.Add(exeType, stringBuilder + ""); } } if (!typeOpenDic.ContainsKey(exeType)) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("不支持的文件格式"); })); } return IntPtr.Zero; } } try { if (intPtr != IntPtr.Zero) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { //HandleHelper.SetParent(proApp.MainWindowHandle, IntPtr.Zero); HandleHelper.ShowWindow(intPtr, (int)ProcessWindowStyle.Hidden); })); } } } catch (Exception) { } //ExitExeMessage(); ExitExeProcess(); if (!filePaths.Contains(filePath)) filePaths.Add(filePath); if (exeType != ExeType.PDF && exeType != ExeType.Pic && exeType != ExeType.Txt && exeType != ExeType.Word && exeType != ExeType.Excel && exeType != ExeType.PPT && exeType != ExeType.WebPage) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.frmWebBrowser.Visible = false; this.spreadSheetEx.Visible = false; this.richEditEx.Visible = false; })); } if (!loadExeProcess.ContainsKey(exeType)) { proApp = new Process(); proApp.StartInfo.FileName = typeOpenDic[exeType]; proApp.StartInfo.Arguments = filePath; proApp.StartInfo.UseShellExecute = true; proApp.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; proApp.Start(); proApp.WaitForInputIdle(); List windowInfos = new List(); while (windowInfos.Count == 0 || windowInfos.Where(n => n.IsVisible).Count() == 0) { windowInfos = HandleHelper.FindAllWindows(x => x.Title != null && x.Title.Contains(Path.GetFileName(filePath))); System.Threading.Thread.Sleep(100); } HandleHelper.WindowInfo formWindowInfo = windowInfos.Where(n => n.IsVisible).FirstOrDefault(); JobControl clsJobControl = new JobControl(); clsJobControl.AddProcess(formWindowInfo.Hwnd); EmbedProcess(formWindowInfo.Hwnd, this.pl_Main); intPtr = formWindowInfo.Hwnd; loadExeProcess.Add(exeType, proApp); } else { proApp = loadExeProcess[exeType]; Process.Start(filePath); List windowInfos = new List(); while (windowInfos.Count == 0 || windowInfos.Where(n => n.IsVisible).Count() == 0) { windowInfos = HandleHelper.FindAllWindows(x => x.Title != null && x.Title.Contains(Path.GetFileName(filePath))); System.Threading.Thread.Sleep(100); } HandleHelper.WindowInfo formWindowInfo = windowInfos.Where(n => n.IsVisible).FirstOrDefault(); JobControl clsJobControl = new JobControl(); clsJobControl.AddProcess(formWindowInfo.Hwnd); EmbedProcess(formWindowInfo.Hwnd, this.pl_Main); intPtr = formWindowInfo.Hwnd; } } else if (exeType == ExeType.PDF || exeType == ExeType.Pic || exeType == ExeType.Txt || exeType == ExeType.PPT || exeType == ExeType.WebPage) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { if (exeType == ExeType.PPT) { string OAUrl = !string.IsNullOrEmpty(SystemInfo.Instance.OAUrl) && SystemInfo.Instance.OAUrl.EndsWith("/") ? SystemInfo.Instance.OAUrl : SystemInfo.Instance.OAUrl + "/"; string preViewUrl = $"{OAUrl}Api/ToolsHandler.ashx?method=ViewDoc&url={ this.url}"; HttpWebResponse httpWebResponse = HttpTools.Post(preViewUrl, "", null, null, HttpTools.Method.GET); downUrl = downUrl.ToLower().Replace("fileroot", "dochtml").Replace("%23", "").Replace(".pptx", "pptx.html").Replace(".ppt", "ppt.html"); } this.frmWebBrowser.Visible = true; this.frmWebBrowser.BringToFront(); this.spreadSheetEx.Visible = false; this.richEditEx.Visible = false; this.frmWebBrowser.LoadUrl(downUrl); })); } } else if (exeType == ExeType.Word) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.richEditEx.Visible = true; this.richEditEx.BringToFront(); this.frmWebBrowser.Visible = false; this.spreadSheetEx.Visible = false; this.richEditEx.RichEditObj.LoadDocument(filePath); })); } } else if (exeType == ExeType.Excel) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.spreadSheetEx.Visible = true; this.spreadSheetEx.BringToFront(); this.frmWebBrowser.Visible = false; this.richEditEx.Visible = false; if (Path.GetExtension(downUrl).Equals(".xls", StringComparison.OrdinalIgnoreCase)) { this.spreadSheetEx.SpreadsheetObj.Document.LoadDocument(filePath, DevExpress.Spreadsheet.DocumentFormat.Xls); } else if (Path.GetExtension(downUrl).Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) { this.spreadSheetEx.SpreadsheetObj.Document.LoadDocument(filePath, DevExpress.Spreadsheet.DocumentFormat.Xlsx); } })); } } lastSaveFilePath = filePath; } catch (Exception ex) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show(ex.Message); })); } } return intPtr; } /// /// 将指定的程序嵌入指定的控件 /// private void EmbedProcess(IntPtr appIntptr, System.Windows.Forms.Control control) { if (appIntptr == IntPtr.Zero || control == null) return; try { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { HandleHelper.SetParent(appIntptr, control.Handle); })); } List results = new List(); while (!results.Contains(appIntptr)) { System.Threading.Thread.Sleep(500); results = new List(); if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { GCHandle listHandle = GCHandle.Alloc(results); try { NativeMethods.EnumWindowProc childProc = new NativeMethods.EnumWindowProc(HandleHelper.EnumWindow); NativeMethods.EnumChildWindows(this.pl_Main.Handle, childProc, GCHandle.ToIntPtr(listHandle)); } finally { if (listHandle.IsAllocated) listHandle.Free(); } if (results.Contains(appIntptr)) { System.Threading.Thread.Sleep(500); HandleHelper.MoveWindow(appIntptr, 0, 0, this.pl_Main.Width, this.pl_Main.Height, true); HandleHelper.ShowWindow(appIntptr, 3); } })); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } #endregion #region 程序操作事件 /// /// 文件双击预载界面 /// /// /// private void OnDoubleClick(object sender, EventArgs e) { if (!this.allowChangeFile) { MessageUtil.Show("请等待当前文档加载完成"); return; } this.allowChangeFile = false; this.TopMost = true; System.Threading.Thread thread = new System.Threading.Thread(() => { try { DataRow mSelectRow = this.fileGrid.GridView.GetFocusedDataRow(); if (!mSelectRow.Table.Columns.Contains("url")) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("未配置附件地址url"); })); } return; } if (!mSelectRow.Table.Columns.Contains("FileName")) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("未配置附件文件名FileName"); })); } return; } if (!mSelectRow.Table.Columns.Contains("idValue")) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("未配置附件idValue"); })); } return; } if (!mSelectRow.Table.Columns.Contains("FileId")) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("未配置附件主键FileId"); })); } return; } if (!mSelectRow.Table.Columns.Contains("FileSize")) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("未配置附件文件大小FileSize"); })); } return; } if (!mSelectRow.Table.Columns.Contains("FileSpeciesNo")) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("未配置附件节点FileSpeciesNo"); })); } return; } this.url = mSelectRow["url"] + ""; this.name = mSelectRow["FileName"] + ""; if (Path.GetExtension(this.name).Equals(".pdf", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(this.name).Equals(".doc", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(this.name).Equals(".docx", StringComparison.OrdinalIgnoreCase)) { this.plSign.Enabled = true; } this.idValue = mSelectRow["idValue"] + ""; int fileId, fileSize; int.TryParse(mSelectRow["FileId"] + "", out fileId); int.TryParse(mSelectRow["FileSize"] + "", out fileSize); string fileSpeciesNo = mSelectRow["FileSpeciesNo"] + ""; if (!string.IsNullOrEmpty(url)) { string tipMsg; int result = GetPermission(2, fileSpeciesNo, fileId, this.name, fileSize, out tipMsg); if (result != 1) { if (!string.IsNullOrEmpty(tipMsg)) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show(tipMsg); })); } } else { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("文件预览权限判断错误"); })); } } return; } string downUrl = url; if (!downUrl.StartsWith("http")) { string OAUrl = !string.IsNullOrEmpty(SystemInfo.Instance.OAUrl) && SystemInfo.Instance.OAUrl.EndsWith("/") ? SystemInfo.Instance.OAUrl : SystemInfo.Instance.OAUrl + "/"; downUrl = OAUrl + downUrl; } fileSavePath = string.Format("{0}\\{1}\\{2}", Application.StartupPath, "ExternalCallFile", name); fileCopyPath = string.Format("{0}\\{1}\\{2}", Application.StartupPath, "ExternalCallCopyFile", "copyFile" + Path.GetExtension(name)); scriptPath = string.Format("{0}\\{1}\\{2}", Application.StartupPath, "ExternalScriptFile", "CloseTab.scr"); if (fileSavePath.Equals(lastSaveFilePath)) { return; } if (!Directory.Exists(Path.GetDirectoryName(fileSavePath))) { Directory.CreateDirectory(Path.GetDirectoryName(fileSavePath)); } if (!Directory.Exists(Path.GetDirectoryName(fileCopyPath))) { Directory.CreateDirectory(Path.GetDirectoryName(fileCopyPath)); } try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downUrl); request.Method = "GET"; WebResponse response = request.GetResponse(); Stream stream = new FileStream(fileSavePath, FileMode.Create, FileAccess.ReadWrite); byte[] bArr = new byte[1024]; int size = response.GetResponseStream().Read(bArr, 0, (int)bArr.Length); while (size > 0) { stream.Write(bArr, 0, size); size = response.GetResponseStream().Read(bArr, 0, (int)bArr.Length); } stream.Close(); response.GetResponseStream().Close(); response.Close(); } catch (Exception) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("服务器异常,文件查找失败"); })); } } this.downFileTime = DateTime.Now; this.Invoke(new Action(() => { this.frmWebBrowser.Visible = false; this.plSign.Enabled = false; this.progressPanel.Visible = true; })); OpenCadExe(fileSavePath, downUrl); this.isAddSign = false; while (!this.InvokeRequired || !this.IsHandleCreated) { System.Threading.Thread.Sleep(100); } this.Invoke(new Action(() => { this.pl_Main.Focus(); })); } } catch (Exception ex) { Console.WriteLine(ex.Message); if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("参数配置错误,请验证配置!"); })); } } finally { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; this.progressPanel.Visible = false; })); } this.allowChangeFile = true; } }); thread.Start(); } /// /// 上传文件 /// /// /// private void OnBackTopClick(object sender, EventArgs e) { if (string.IsNullOrEmpty(fileSavePath)) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("文件不存在"); })); } return; } if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(idValue)) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; MessageUtil.Show("未预载文件请双击打开后再上传!"); })); } return; } try { File.Copy(fileSavePath, fileCopyPath, true); DataRow mSelectRow = this.fileGrid.GridView.GetFocusedDataRow(); this.url = mSelectRow["url"] + ""; this.name = mSelectRow["FileName"] + ""; this.idValue = mSelectRow["idValue"] + ""; int fileId; int.TryParse(mSelectRow["FileId"] + "", out fileId); string fileSpeciesNo = mSelectRow["FilespeciesNo"] + ""; byte[] fileBytes = ConvertFileToBytes(fileCopyPath); int fileSize = fileBytes != null ? fileBytes.Length : 0; string tipMsg; int allowUpdate = GetPermission(1, fileSpeciesNo, fileId, this.name, fileSize, out tipMsg); if (allowUpdate != 1) { if (this.InvokeRequired && this.IsHandleCreated) { this.Invoke(new Action(() => { this.TopMost = false; if (!string.IsNullOrEmpty(tipMsg)) { MessageUtil.Show(tipMsg); } else { MessageUtil.Show("文件修改权限判断错误"); } })); } return; } FileInfo fileInfo = new FileInfo(fileCopyPath); if (fileInfo.LastWriteTime <= downFileTime) { this.TopMost = false; DialogResult dialogResult = MessageUtil.Show("文件未更新,请修改后上传", MessageBoxButtons.OK); this.pl_Main.Focus(); return; } fileBytes = ConvertFileToBytes(fileCopyPath); string fileBase64Str = Convert.ToBase64String(fileBytes) + ""; string postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&folder={3}&totsize={4}&position={5}&filename={6}&username={7}&userid={8}&method={9}"; postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, this.SysModel.ModuleCode, this.idValue, "UploadFilesTemp", fileBytes.Length, 0, this.name, ERPInfo.Instance.UserName, ERPInfo.Instance.UserId, "DoWebUpload"); //string postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&folder={3}&totsize={4}&position={5}&filename={6}&method={7}"; //postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, this.SysModel.ModuleCode, this.SysModel.idValue, "UploadFilesTemp", fileBytes.Length, 0, this.SysModel.name, "DoWebUpload"); HttpTools.setting("application/x-www-form-urlencoded", null, null); string result = ""; CookieCollection cookieCollection = null; HttpWebResponse webResponse = HttpTools.Post(postUrl, fileBase64Str, null, HttpTools.Method.POST, out cookieCollection, out result); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject jsonObject = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); string isSuccess = jsonObject["success"] + ""; if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase)) { this.TopMost = false; MessageUtil.Show("上传成功"); RefDataSource(); } else { string msg = ""; if (jsonObject.ContainsKey("msg")) { msg = jsonObject["msg"] + ""; } if (!string.IsNullOrEmpty(msg)) { this.TopMost = false; MessageUtil.Show(string.Format("上传失败,原因:{0}", msg)); } else { this.TopMost = false; MessageUtil.Show("上传失败"); } } } else { this.TopMost = false; MessageUtil.Show("上传失败"); } } catch (Exception ex) { this.TopMost = false; MessageUtil.Show(string.Format("上传失败,原因:{0}", ex.Message)); } } #endregion /// /// 固定关闭按钮触发事件 /// /// /// private void OnplCloseing(object sender, EventArgs e) { try { this.DialogResult = DialogResult.Cancel; this.Close(); } catch (Exception) { } } /// /// 程序关闭时关闭所有相关进程 /// /// /// private void OnFormClosing(object sender, FormClosingEventArgs e) { try { ExitExeProcess(); //ExitExeProcess(); string fileSaveDir = string.Format("{0}\\{1}", Application.StartupPath, "ExternalCallFile"); string fileCopyDir = string.Format("{0}\\{1}", Application.StartupPath, "ExternalCallCopyFile"); if (Directory.Exists(fileSaveDir)) { Directory.Delete(fileSaveDir, true); } if (Directory.Exists(fileCopyDir)) { Directory.Delete(fileCopyDir, true); } } catch (Exception) { } } /// /// 退出关联进程 /// private void ExitExeMessage(ExeType exitType = ExeType.All) { if (this.exeType != ExeType.PDF && proApp != null && proApp.HasExited == false) { try { HandleHelper.SendMessage(intPtr, WM_CLOSE, 0, 0); System.Threading.Thread.Sleep(1000); while (!proApp.HasExited) { System.Threading.Thread.Sleep(1000); } } catch (Exception) { } } } private void ExitExeProcess(ExeType exitType = ExeType.All) { foreach (Process process in Process.GetProcesses()) { switch (exitType) { case ExeType.Cad: if (process.ProcessName.Equals("acad", StringComparison.OrdinalIgnoreCase)) { process.Kill(); process.WaitForExit(); } break; case ExeType.Word: if (process.ProcessName.Equals("WINWORD", StringComparison.OrdinalIgnoreCase) || process.ProcessName.Equals("wps", StringComparison.OrdinalIgnoreCase)) { process.Kill(); process.WaitForExit(); } break; case ExeType.Excel: if (process.ProcessName.Equals("EXCEL", StringComparison.OrdinalIgnoreCase) || process.ProcessName.Equals("et", StringComparison.OrdinalIgnoreCase)) { process.Kill(); process.WaitForExit(); } break; //case ExeType.PPT: // if (process.ProcessName.Equals("POWERPNT", StringComparison.OrdinalIgnoreCase) || process.ProcessName.Equals("wpp", StringComparison.OrdinalIgnoreCase)) // { // process.Kill(); // process.WaitForExit(); // } // break; case ExeType.All: if (process.ProcessName.Equals("acad", StringComparison.OrdinalIgnoreCase) || //process.ProcessName.Equals("et", StringComparison.OrdinalIgnoreCase) || //process.ProcessName.Equals("wpp", StringComparison.OrdinalIgnoreCase) || //process.ProcessName.Equals("wpscloudsvr", StringComparison.OrdinalIgnoreCase) || //process.ProcessName.Equals("wps", StringComparison.OrdinalIgnoreCase) || //process.ProcessName.Equals("WINWORD", StringComparison.OrdinalIgnoreCase) || //process.ProcessName.Equals("EXCEL", StringComparison.OrdinalIgnoreCase) || process.ProcessName.Equals("POWERPNT", StringComparison.OrdinalIgnoreCase)) { process.Kill(); process.WaitForExit(); } break; } } if (!string.IsNullOrEmpty(lastSaveFilePath) && !lastSaveFilePath.Equals(fileSavePath) && File.Exists(lastSaveFilePath))//删除上一次下载的文件 { File.Delete(lastSaveFilePath); } if (this.loadExeProcess.ContainsKey(exitType)) { this.loadExeProcess.Remove(exitType); } } /// /// 附件转换byte[] /// /// 附件路径 /// 二进制 private byte[] ConvertFileToBytes(string filePath) { byte[] bytContent = null; System.IO.FileStream fs = null; System.IO.BinaryReader br = null; try { fs = new FileStream(filePath, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception) { throw; } if (fs != null) br = new BinaryReader((Stream)fs); if (br != null) bytContent = br.ReadBytes((Int32)fs.Length); if (fs != null) fs.Dispose(); return bytContent; } /// /// 分割条位置改变时 /// /// /// private void OnSplitterPositionChanged(object sender, EventArgs e) { if (!isFirstOpen) { IniHelper.Write(string.Format("EmbeCadSpliterPositionMain_{0}", this.SysModel.ModuleCode), this.splitMainContainer.SplitterDistance + ""); } isFirstOpen = false; } /// /// 窗体大小改变 /// /// /// private void OnSizeChanged(object sender, EventArgs e) { if (intPtr != IntPtr.Zero) { HandleHelper.SetParent(intPtr, this.pl_Main.Handle); HandleHelper.MoveWindow(intPtr, 0, 0, this.pl_Main.Width, this.pl_Main.Height, true); HandleHelper.ShowWindow(intPtr, 3); } if (this.frmWebBrowser.Visible && this.frmWebBrowser.cefBrowserSettings != null) { var handle = this.frmWebBrowser.cefBrowserSettings.GetHost().GetWindowHandle(); this.frmWebBrowser.ResizeWindow(handle, this.pl_Main.Width, this.pl_Main.Height); } } /// /// 刷新表格数据 /// private void RefDataSource() { try { int index = this.fileGrid.GridView.FocusedRowHandle; this.mainSql = string.IsNullOrWhiteSpace(SysModel.ControlSql) ? Model.MenuSql : ReplaceHelper.ReplaceRowParam(MainImpl.GetDataRowResult(SysModel.ControlSql), Model.MenuSql); DataTable dataTable = MainImpl.GetDataTableResult(mainSql); this.fileGrid.gridControl.DataSource = dataTable; this.fileGrid.GridView.BestFitColumns(); this.fileGrid.GridView.FocusedRowHandle = index; } catch (Exception ex) { this.TopMost = false; MessageUtil.Show(ex.Message); } } /// /// 是否存在autoCad进程 /// /// private bool IsExitCadProgress() { bool isExit = false; try { foreach (Process process in Process.GetProcesses()) { if (process.ProcessName.Equals("acad", StringComparison.OrdinalIgnoreCase)) { isExit = true; break; } } } catch (Exception) { } return isExit; } /// /// 获取权限 /// private int GetPermission(int opertype, string fileSpecisNo, int fileid, string filename, int filesize, out string tipMsg) { try { SqlParameter pMsg = new SqlParameter("@msg", SqlDbType.VarChar, 2000); pMsg.Direction = ParameterDirection.Output; SqlParameter returnValue = new SqlParameter("@return", SqlDbType.Int, 4); returnValue.Direction = ParameterDirection.ReturnValue; SqlParameter[] param = { new SqlParameter("@opertype",SqlDbType.Int), new SqlParameter("@operatorid ",SqlDbType.Int), new SqlParameter("@operatorname ",SqlDbType.VarChar,20), new SqlParameter("@fileSpecisNo",SqlDbType.VarChar,20), new SqlParameter("@fileid",SqlDbType.Int), new SqlParameter("@filename",SqlDbType.VarChar,200), new SqlParameter("@filesize",SqlDbType.Int), pMsg, returnValue }; param[0].Value = opertype; param[1].Value = ERPInfo.Instance.UserId; param[2].Value = ERPInfo.Instance.UserName; param[3].Value = fileSpecisNo; param[4].Value = fileid; param[5].Value = filename; param[6].Value = filesize; param[7].Value = ""; DataSet dataSet = SqlHelper.ExecuteDataSet(CommandType.StoredProcedure, "p_SystemAttachOperation", "attachOperation", param); tipMsg = pMsg.Value.ToString(); return Convert.ToInt32(returnValue.Value + ""); } catch (Exception ex) { tipMsg = ex.Message; } return -1; } /// /// 添加签章到PDF /// /// /// /// private void AddSignToPDF(string signImageUrl, string sourcePath, string savePath) { try { using (FileStream fileStream = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite)) { using (iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(sourcePath)) { PdfStamper stamper = new PdfStamper(reader, fileStream); int readPageNum = reader.NumberOfPages; PdfContentByte pdfContentByte = stamper.GetOverContent(1);//获取第1页内容 using (WebClient webClient = new WebClient()) { using (Stream stream = webClient.OpenRead(signImageUrl)) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(stream);//获取签章图片 image.ScaleAbsolute(200, 100);//设置图片比例 image.SetAbsolutePosition(200, 100);//设置图片的绝对位置 pdfContentByte.AddImage(image); } } stamper.Close(); } } } catch (Exception ex) { this.TopMost = false; MessageUtil.Show(ex.Message); } } /// /// 说明:word通过当前名字自动签章 /// 创建人:王一帆 /// 创建日期:2023-11-08 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// 插入图层的地址 public void wordInsertlayer(string signImageUrl, string sourcePath) { // 创建文档对象 Document document = new Document(); // 加载文档 document.LoadFromFile(sourcePath); // 获取第一个节 Section section = document.Sections[0]; // 创建图片对象 DocPicture picture = new DocPicture(document); // 加载图片 picture.LoadImage(signImageUrl); // 设置图片的绝对位置 picture.HorizontalPosition = 50.0f; // 水平位置,单位磅 picture.VerticalPosition = 100.0f; // 垂直位置,单位磅 // 设置图片布局为浮动,这样可以设置绝对位置 picture.TextWrappingStyle = TextWrappingStyle.Square; picture.TextWrappingType = TextWrappingType.Both; // 选择图片位置的参考点 picture.HorizontalOrigin = HorizontalOrigin.Page; picture.VerticalOrigin = VerticalOrigin.Page; // 将图片添加到节的子对象中 section.ChildObjects.Add(picture); // 保存文档 document.SaveToFile(sourcePath); } /// /// 签章按钮事件 /// /// /// private void plSign_Click(object sender, EventArgs e) { WaitForm.ShowForm(); try { if (string.IsNullOrEmpty(fileSavePath)) { this.TopMost = false; MessageUtil.Show("文件不存在"); return; } if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(idValue)) { this.TopMost = false; MessageUtil.Show("未预载文件"); return; } if (isAddSign) { this.TopMost = false; MessageUtil.Show("当前文件已添加签章"); return; } string signUrl = ""; if (exeType == ExeType.PDF) { AddSignToPDF(signUrl, fileSavePath, fileCopyPath); File.Copy(fileCopyPath, fileSavePath, true); this.frmWebBrowser.LoadUrl(fileSavePath); this.isAddSign = true; } else if (exeType == ExeType.Word) { File.Copy(fileSavePath, fileCopyPath, true); wordInsertlayer(signUrl, fileCopyPath); this.richEditEx.CloseDocument(); File.Copy(fileCopyPath, fileSavePath, true); this.richEditEx.RichEditObj.LoadDocument(fileSavePath); this.isAddSign = true; } this.TopMost = false; MessageUtil.Show("添加签章成功"); } catch (Exception ex) { this.TopMost = false; MessageUtil.Show(ex.Message); } WaitForm.HideForm(); } /// /// 隐藏进程 /// //private void HideProcess() //{ // foreach (string filePath in filePaths) // { // try // { // if (!filePath.Equals(this.fileSavePath)) // { // List windowInfos = HandleHelper.FindAllWindows(x => x.Title.Contains(Path.GetFileName(filePath))); // foreach (HandleHelper.WindowInfo windowInfo in windowInfos) // { // HandleHelper.ShowWindow(windowInfo.Hwnd, 0); // //HandleHelper.SendMessage(windowInfo.Hwnd, WM_CLOSE, 0, 0); // } // //HandleHelper.ShowWindow(windowInfo.Hwnd, 0); // } // } // catch (Exception) // { // } // } //} } }