using Accord.Video.FFMPEG; using Aspose.Slides; using ComeCapture; using Common.system; using NAudio.Wave; using NReco.VideoConverter; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Threading; using TmatrixLibrary; using XHWK.Model; using XHWK.WKTool.Models; using XHWK.WKTool.Skin; using XHWK.WKTool.UControl; using XHWK.WKTool.Utils; using XHWK.WKTool.Utils.luobo; using XHWK.WKTool.Utils.pen; namespace XHWK.WKTool { /// /// 主页面 /// public partial class MainWindow : Window, PenEventI { #region 字段 public BlackboardNew myblackboard; /// /// 当前颜色 /// private System.Windows.Media.Color Color = Colors.Red; //声明一个 DrawingAttributes 类型的变量 private DrawingAttributes drawingAttributes; /// /// 键盘钩子 /// private KeyboardHookCommon k_hook; private System.Windows.Forms.OpenFileDialog ofd; private System.Windows.Forms.FolderBrowserDialog Ofd; /// /// 页码下拉列表 /// private List PageData = null; /// /// 笔迹粗细 /// private int PenSize = 2; private System.Windows.Forms.DialogResult result; private System.Windows.Forms.DialogResult Result; private Model_Video VideoInfo = null; ////定义事件 //public event ChangeTextHandler ChangeTextEvent; //定义委托 public delegate void ChangeTextHandler(string text); //定义委托 public delegate void ChangeTextHandlers(string text, int i); //private DispatcherTimer t = null; /// /// 计时器状态 /// private enum State { Start, Pause, End } #region 上传 /// /// 数据列表 /// internal FileDirectoryData pageData = new FileDirectoryData(); /// /// 视频模型 /// private List model_VideoList = null; #endregion 上传 #endregion 字段 #region 初始化 private ImageOperationUtil imageOperationUtil; private LuoBoPenUtil luoBoPenUtil; /// /// 主页面 /// public MainWindow() { InitializeComponent(); #region 调整文字大小 APP.PageContextData.WordSize20 = 20.00; APP.PageContextData.WordSize18 = 18.00; APP.PageContextData.WordSize16 = 16.00; APP.PageContextData.WordSize14 = 14.00; APP.PageContextData.WordSize12 = 12.00; #endregion 调整文字大小 ResizeMode = ResizeMode.CanMinimize; BtnPrint.IsEnabled = false; myblackboard = new BlackboardNew(blackboard_canvas); APP.PageContextData.pagenum = 0; APP.PageContextData.currpage = 0; DataContext = APP.PageContextData; //APP.SaveDraw();//画板模型第一页初始化 APP.PageDrawList = new List(); Model_DrawData model_DrawData = new Model_DrawData { PageNum = APP.PageContextData.currpage }; APP.PageDrawList.Add(model_DrawData); txbv.Text = "v" + FileToolsCommon.GetConfigValue("VersionName"); txbStoragePath.Content = FileToolsCommon.GetConfigValue("VideoType"); txbStoragePath.Content = FileToolsCommon.GetConfigValue("VideoSavePath"); Initialize(); //罗博手写板 luoBoPenUtil = new LuoBoPenUtil(this); luoBoPenUtil.InitlbPen(); //腾千里 InitTQLPPen(); SkinSelectInit(); byte[] license = Convert.FromBase64String("PExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5TdXpob3UgQXVuYm94IFNvZnR3YXJlIENvLiwgTHRkLjwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPnNhbGVzQGF1bnRlYy5jb208L0VtYWlsVG8+CiAgICA8TGljZW5zZVR5cGU+RGV2ZWxvcGVyIE9FTTwvTGljZW5zZVR5cGU+CiAgICA8TGljZW5zZU5vdGU+TGltaXRlZCB0byAxIGRldmVsb3BlciwgdW5saW1pdGVkIHBoeXNpY2FsIGxvY2F0aW9uczwvTGljZW5zZU5vdGU+CiAgICA8T3JkZXJJRD4xOTA4MjYwODA3NTM8L09yZGVySUQ+CiAgICA8VXNlcklEPjEzNDk3NjAwNjwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIGZvciAuTkVUPC9Qcm9kdWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+M2U0NGRlMzAtZmNkMi00MTA2LWIzNWQtNDZjNmEzNzE1ZmMyPC9TZXJpYWxOdW1iZXI+CiAgICA8U3Vic2NyaXB0aW9uRXhwaXJ5PjIwMjAwODI3PC9TdWJzY3JpcHRpb25FeHBpcnk+CiAgICA8TGljZW5zZVZlcnNpb24+My4wPC9MaWNlbnNlVmVyc2lvbj4KICAgIDxMaWNlbnNlSW5zdHJ1Y3Rpb25zPmh0dHBzOi8vcHVyY2hhc2UuYXNwb3NlLmNvbS9wb2xpY2llcy91c2UtbGljZW5zZTwvTGljZW5zZUluc3RydWN0aW9ucz4KICA8L0RhdGE+CiAgPFNpZ25hdHVyZT53UGJtNUt3ZTYvRFZXWFNIY1o4d2FiVEFQQXlSR0pEOGI3L00zVkV4YWZpQnd5U2h3YWtrNGI5N2c2eGtnTjhtbUFGY3J0c0cwd1ZDcnp6MytVYk9iQjRYUndTZWxsTFdXeXNDL0haTDNpN01SMC9jZUFxaVZFOU0rWndOQkR4RnlRbE9uYTFQajhQMzhzR1grQ3ZsemJLZFZPZXk1S3A2dDN5c0dqYWtaL1E9PC9TaWduYXR1cmU+CjwvTGljZW5zZT4="); new Aspose.Words.License().SetLicense(new MemoryStream(license)); new Aspose.Pdf.License().SetLicense(new MemoryStream(license)); new Aspose.Slides.License().SetLicense(new MemoryStream(license)); imageOperationUtil = new ImageOperationUtil( RectLeftUp, RectRightUp, RectLeftDown, RectRightDown, RectImgBorder, imgCanvas, GridM); InitPrint(); } /// /// 初始化 /// public void Initialize() { if (APP.isDebug) { txbVersion.Text = "测试版:"; } else { txbVersion.Text = "正式版:"; } #region 数据初始化 string pathTemp = AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; FileToolsCommon.CreateDirectory(pathTemp); APP.PageContextData.pagenum = 0; APP.PageContextData.currpage = APP.PageContextData.pagenum; BtnStop.IsEnabled = false;//停止录制按钮不可点击 #endregion 数据初始化 k_hook = new KeyboardHookCommon(); k_hook.KeyDownEvent += K_hook_KeyDownEvent; k_hook.Start();//安装键盘钩子 APP.CameraPosition = FileToolsCommon.GetConfigValue("CameraPosition"); //创建 DrawingAttributes 类的一个实例 drawingAttributes = new DrawingAttributes(); //将 InkCanvas 的 DefaultDrawingAttributes 属性的值赋成创建的 DrawingAttributes 类的对象的引用 //InkCanvas 通过 DefaultDrawingAttributes 属性来获取墨迹的各种设置,该属性的类型为 DrawingAttributes 型 blackboard_canvas.DefaultDrawingAttributes = drawingAttributes; blackboard_canvas.UseCustomCursor = true; drawingAttributes.FitToCurve = true; drawingAttributes.IgnorePressure = false; drawingAttributes.Width = PenSize; drawingAttributes.Height = PenSize; drawingAttributes.Color = Color; blackboard_canvas.Cursor = Cursors.Pen; } /// /// 初始化快捷键 /// public void InitializeKeyDownEvent() { k_hook.Start();//安装键盘钩子 } /// /// 引用user32.dll动态链接库(windows api), 使用库中定义 API:SetCursorPos 设置光标位置 /// [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern int SetCursorPos(int x, int y); /// /// 快捷键 /// /// /// /// /// private void K_hook_KeyDownEvent(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyValue == (int)System.Windows.Forms.Keys.Left) { if (APP.PageContextData.currpage > 1) { //上一页 last_button_Click(null, null); } } if (e.KeyValue == (int)System.Windows.Forms.Keys.Right) { if (APP.PageContextData.currpage < APP.PageContextData.pagenum) { //下一页 next_btn_Click(null, null); } } if (e.KeyValue == (int)System.Windows.Forms.Keys.Delete) { if (RectImgBorder.Visibility != Visibility.Hidden) { HideAngleBorder(); imgCanvas.Source = null; APP.PageDrawList[APP.PageContextData.currpage - 1].PdfImagePath = null; APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath = null; } } } /// /// 加载完成后调整录制区域大小 /// /// /// /// /// private async void Window_Loaded(object sender, RoutedEventArgs e) { //调整录制区域宽高 double proportion = 210.0 / 297.0; GridM.Height = GridM.ActualWidth / proportion; await checkDevice(); } private bool microphoneGood = false; private bool loudspeakerGood = false; private async Task checkDevice() { Task checkMicrophone = Task.Run(() => { return ZAudioRecordHelper.IsDeviceGood(ZAudioRecordHelper.RecordType.microphone); } ); Task checkLoudspeaker = Task.Run( () => { return ZAudioRecordHelper.IsDeviceGood(ZAudioRecordHelper.RecordType.loudspeaker); }); await Task.WhenAll(checkMicrophone, checkLoudspeaker); microphoneGood = checkMicrophone.Result; loudspeakerGood = checkMicrophone.Result; } #endregion 初始化 #region 事件 #region 登录 /// /// 登录事件 /// /// /// /// /// private void BtnLoginType_Click(object sender, RoutedEventArgs e) { if ("未登录".Equals(TxbLoginType.Text) || ImgHeadImgN.Visibility == Visibility.Visible) { Login(); } else { MessageBoxResult dr = MessageWindow.Show("确定退出登录?", "提示", MessageBoxButton.OKCancel); if (dr == MessageBoxResult.OK) { LoginType(); Login(); } } } /// /// 登录 /// private void Login() { if (APP.W_LoginWindow == null) { APP.W_LoginWindow = new LoginWindow { WindowStartupLocation = WindowStartupLocation.CenterOwner, Owner = this }; } else { APP.W_LoginWindow.Initialize(); } APP.W_LoginWindow.ShowDialog(); if (APP.IsLoginType) { string HeadpicPath = FileToolsCommon.GetFileAbsolutePath("/Data/" + APP.UserInfo.Username + ".png"); if (FileToolsCommon.IsExistFile(HeadpicPath)) { ImgHead.ImageSource = new BitmapImage(new Uri(HeadpicPath)); } else { ImgHead.ImageSource = new BitmapImage(new Uri("pack://application:,,,/BlackImages/HM_HeadImg.png")); } TxbLoginType.Text = APP.UserInfo.Username; ImgHeadImgN.Visibility = Visibility.Collapsed; ImgHeadImg.Visibility = Visibility.Visible; } else { TxbLoginType.Text = "未登录"; ImgHeadImgN.Visibility = Visibility.Visible; ImgHeadImg.Visibility = Visibility.Collapsed; } } /// /// 状态更改为未登录 /// private void LoginType() { APP.IsLoginType = false; TxbLoginType.Text = "未登录"; ImgHeadImgN.Visibility = Visibility.Visible; ImgHeadImg.Visibility = Visibility.Collapsed; APP.UserInfo = new Model_UserInfo(); //ImgUpload.Visibility = Visibility.Collapsed; //ImgUploadTwo.Visibility = Visibility.Visible; } #endregion 登录 #region 设置 /// /// 设置 浏览事件 /// /// /// /// /// private void BtnBrowse_Click(object sender, RoutedEventArgs e) { //System.Diagnostics.Process.Start(APP.WKData.WkPath); //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); Ofd = new System.Windows.Forms.FolderBrowserDialog(); Result = Ofd.ShowDialog(); if (Result == System.Windows.Forms.DialogResult.OK) { if (Ofd.SelectedPath != "") { txbStoragePath.Content = Ofd.SelectedPath; } } } /// /// 打开文件所在位置 /// /// /// /// /// private void btnOpen_Click(object sender, RoutedEventArgs e) { Process.Start(APP.WKData.WkPath); } /// /// 设置 保存事件 /// /// /// /// /// private void BtnSave_Click(object sender, RoutedEventArgs e) { try { BtnRecord.IsEnabled = true;//设置结束时可录制 if (rbnMP4.IsChecked == true) { //存储文件 FileToolsCommon.SetConfigValue("VideoType", "1"); } else if (rbnFLV.IsChecked == true) { FileToolsCommon.SetConfigValue("VideoType", "2"); } else { FileToolsCommon.SetConfigValue("VideoType", "3"); } UpdateHideSRToolConfig(); /// < !--摄像头位置 1.右上 2.左上 3.右下 4.左下-- > if (rbnRight.IsChecked == true) { FileToolsCommon.SetConfigValue("CameraPosition", "1"); } else if (rbnLeft.IsChecked == true) { FileToolsCommon.SetConfigValue("CameraPosition", "2"); } else if (rbnRightUnder.IsChecked == true) { FileToolsCommon.SetConfigValue("CameraPosition", "3"); } else if (rbnLeftUnder.IsChecked == true) { FileToolsCommon.SetConfigValue("CameraPosition", "4"); } //格式 if (rbnMP4.IsChecked == true) { FileToolsCommon.SetConfigValue("VideoType", "1"); } else if (rbnFLV.IsChecked == true) { FileToolsCommon.SetConfigValue("VideoType", "2"); } else if (rbnAVI.IsChecked == true) { FileToolsCommon.SetConfigValue("VideoType", "3"); } APP.CameraPosition = FileToolsCommon.GetConfigValue("CameraPosition"); GridMain.Visibility = Visibility.Visible; GridM.IsEnabled = true; GridRecordingTitle.Visibility = Visibility.Visible; gridSetUp.Visibility = Visibility.Collapsed; imgPlayerRight.Visibility = Visibility.Collapsed; imgPlayerLeft.Visibility = Visibility.Collapsed; imgPlayerRightUnder.Visibility = Visibility.Collapsed; imgPlayerLeftUnder.Visibility = Visibility.Collapsed; if (!txbStoragePath.Content.ToString().Equals(APP.WKData.WkPath)) { //存储文件 FileToolsCommon.SetConfigValue("VideoSavePath", txbStoragePath.Content.ToString()); MessageWindow.Show("路径已变更,下次创建微课时自动生效。"); } } catch (Exception ex) { LogHelper.WriteErrLog("XHMicroLessonSystemWindow(设置保存事件报错:)" + ex.Message, ex); } } /// /// 设置事件 /// /// /// /// /// private void BtnSetUp_Click(object sender, RoutedEventArgs e) { if (gridSetUp.Visibility == Visibility.Collapsed) { PageHide(); gridSetUp.Visibility = Visibility.Visible; txbStoragePath.Content = APP.WKData.WkPath; #region 读取用户配置 /// < !--摄像头位置 1.右上 2.左上 3.右下 4.左下-- > if ("1".Equals(APP.CameraPosition)) { rbnRight.IsChecked = true; } else if ("2".Equals(APP.CameraPosition)) { rbnLeft.IsChecked = true; } else if ("3".Equals(APP.CameraPosition)) { rbnRightUnder.IsChecked = true; } else if ("4".Equals(APP.CameraPosition)) { rbnLeftUnder.IsChecked = true; } string type = FileToolsCommon.GetConfigValue("VideoType");// if ("1".Equals(type)) { rbnMP4.IsChecked = true; } else if ("2".Equals(type)) { rbnFLV.IsChecked = true; } else if ("3".Equals(type)) { rbnAVI.IsChecked = true; } string isHide = FileToolsCommon.GetConfigValue("IsHideSRTool"); //工具栏是否隐藏 if (isHide.Equals("1")) { rbnHide.IsChecked = true; } else { rbnvisi.IsChecked = true; } //string isSound = FileToolsCommon.GetConfigValue("IsSound");// //if (isSound == "true") //{ // rbnY.IsChecked = true; //} //else //{ // rbnN.IsChecked = true; //} //加载皮肤按钮 SkinSelectInit(); #endregion 读取用户配置 } else { GridMain.Visibility = Visibility.Visible; GridM.IsEnabled = true; GridRecordingTitle.Visibility = Visibility.Visible; gridSetUp.Visibility = Visibility.Collapsed; } } /// /// 更新隐藏录屏工具栏隐藏状态 /// private void UpdateHideSRToolConfig() { if (rbnHide.IsChecked == true) { //隐藏 FileToolsCommon.SetConfigValue("IsHideSRTool", "1"); APP.IsHideSRTool = true; } else { //显示 FileToolsCommon.SetConfigValue("IsHideSRTool", "0"); APP.IsHideSRTool = false; } } #region 切换皮肤 /// /// 科技蓝 /// /// /// /// /// private void BtnSkinTechnologyBlue_Click(object sender, RoutedEventArgs e) { if (APP.SkinStyle != "1") { HideSkinSelect(); SkinSelectTechnologyBlue.Visibility = Visibility.Visible; APP.SkinStyle = "1"; FileToolsCommon.SetConfigValue("SkinStyle", "1"); SkinConfig.SwitchSkin(1); } } /// /// 白色 /// /// /// /// /// private void BtnSkinWhite_Click(object sender, RoutedEventArgs e) { if (APP.SkinStyle != "0") { HideSkinSelect(); SkinSelectWhite.Visibility = Visibility.Visible; APP.SkinStyle = "0"; FileToolsCommon.SetConfigValue("SkinStyle", "0"); SkinConfig.SwitchSkin(0); } } /// /// 隐藏皮肤选择键 /// private void HideSkinSelect() { SkinSelectWhite.Visibility = Visibility.Hidden; SkinSelectTechnologyBlue.Visibility = Visibility.Hidden; } /// /// 加载皮肤选项 /// private void SkinSelectInit() { if (APP.SkinStyle == "0") { HideSkinSelect(); SkinSelectWhite.Visibility = Visibility.Visible; SkinConfig.SwitchSkin(0); } else if (APP.SkinStyle == "1") { HideSkinSelect(); SkinSelectTechnologyBlue.Visibility = Visibility.Visible; SkinConfig.SwitchSkin(1); } else { HideSkinSelect(); SkinSelectWhite.Visibility = Visibility.Visible; } } #endregion 切换皮肤 #endregion 设置 private bool isHasCode = false; /// /// 增加事件 /// /// /// /// /// private void BtnAdd_Click(object sender, RoutedEventArgs e) { luoBoPenUtil.lb_device_hand(); Record(); if (APP.PageContextData.currpage > 0) { APP.PageDrawList[APP.PageContextData.currpage - 1].IsImageLocation = true; } if (blackboard_canvas.Visibility == Visibility.Collapsed) { blackboard_canvas.Visibility = Visibility.Visible; } APP.PageContextData.pagenum += 1; HideAngleBorder(); GridPage.Visibility = Visibility.Visible;//页码大于0 显示 APP.PageContextData.currpage = APP.PageContextData.pagenum; myblackboard.changepage(APP.PageContextData.currpage - 1); ScroMain.ScrollToVerticalOffset(0); ///清空页面图片UI imgCanvas.Source = null; imgDocumentation.Source = null; imgPPT.Source = null; if (APP.PageContextData.pagenum == 1) { APP.PageDrawList = new List(); } ///画板模型增加一页 Model_DrawData model_DrawData = new Model_DrawData { PageNum = APP.PageContextData.currpage }; APP.PageDrawList.Add(model_DrawData); if (RecordType == 0) { BtnPrint.IsEnabled = true; } //APP.SaveDraw(); if (BtnImport.IsEnabled) { ///截图可用 BtnScreenshot.IsEnabled = true; } #region 插入页码 PageData = new List(); for (int i = 1; i <= APP.PageContextData.pagenum; i++) { PageData pd = new PageData(); pd.PageName = i.ToString();// + "页"; pd.PageCode = i; PageData.Add(pd); } #endregion 插入页码 } /// /// 关闭事件 /// /// /// /// /// private void BtnClose_Click(object sender, RoutedEventArgs e) { if (RecordType == 0) { try { MessageBoxResult br = MessageWindow.Show("确定退出系统?", "退出", MessageBoxButton.OKCancel); if (br == MessageBoxResult.OK) { try { APP.Killffmpeg(); } catch (Exception ex) { LogHelper.WriteErrLog("获取进程失败," + ex.Message, ex); } APP.SaveWkData(); APP.SaveDraw(); TMC.TmatrixUninitialize(); Environment.Exit(0); } } catch (Exception ex) { LogHelper.WriteErrLog("关闭微课失败," + ex.Message, ex); Close(); Application.Current.Shutdown(); TMC.TmatrixUninitialize(); Environment.Exit(0); } } else { MessageWindow.Show("当前正在录制,请先停止录制。"); return; } } /// /// 打印事件 /// /// /// /// /// private void BtnPrint_Click(object sender, RoutedEventArgs e) { try { //3种情况 1.文档图片 2.截图图片 3.没有图片 if (APP.PageDrawList.Count == 0) { MessageWindow.Show("没有可打印的页,您可以通过加页、截图或导入来增加页!"); return; } } catch (Exception ex) { MessageWindow.Show(ex.Message); Console.WriteLine("转换失败,原因:" + ex.Message); } if (GridPrintingTitle.Visibility == Visibility.Visible) { GridPrintingTitle.Visibility = Visibility.Collapsed; } else { GridPrintingTitle.Visibility = Visibility.Visible; if (APP.PageDrawList.Count > 0 && !string.IsNullOrWhiteSpace(APP.PageDrawList[0].PageImagePath)) { InitializePrint(APP.PageDrawList[0].PageImagePath, GridM.ActualWidth, GridM.ActualHeight); } else { InitializePrint("", GridM.ActualWidth, gridActHeight); } } } /// /// 打印 /// /// /// /// /// private void BtnPrint_Print_Click(object sender, RoutedEventArgs e) { isHasCode = true; print(); } private void BtnPrintCloseClick(object sender, RoutedEventArgs e) { GridPrintingTitle.Visibility = Visibility.Collapsed; } /// /// 打印说明 /// /// /// /// /// private void btnPrintExplain_Click(object sender, RoutedEventArgs e) { Process.Start(FileToolsCommon.GetFileAbsolutePath("/星火微课点阵码打印及印刷指导手册.docx")); } private void PageHide() { //设置 gridSetUp.Visibility = Visibility.Collapsed; //我的 GridMyVideo.Visibility = Visibility.Collapsed; //首页 GridMain.Visibility = Visibility.Collapsed; GridM.IsEnabled = true; //打印 GridPrintContent.Visibility = Visibility.Collapsed; //标题 录制 GridRecordingTitle.Visibility = Visibility.Collapsed; //标题 打印 GridPrintingTitle.Visibility = Visibility.Collapsed; } private void print() { if (string.IsNullOrWhiteSpace(cmbClass.Text)) { MessageWindow.Show("请设置打印机!"); return; } BtnPrint.IsEnabled = false; PrintModel printmodel = new PrintModel(); string imgPath = FileToolsCommon.GetFileAbsolutePath("temp/"); imgPath = imgPath + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf"; printmodel.filepath = imgPath; //打印数量 printmodel.num = 1; //打印机名称 string PrinterName = cmbClass.Text; printmodel.printname = PrinterName; PrintMsg = "准备中"; msgnum = 0; num = 0; GridPrintMask.Visibility = Visibility.Visible; Task.Run(() => { StartPrint(printmodel); }); timesPrint = new System.Timers.Timer(100); timesPrint.Elapsed += Times_ElapsedClick; timesPrint.Start(); timesPrintMsg = new System.Timers.Timer(500); timesPrintMsg.Elapsed += TimesPrintMsg_Elapsed; timesPrintMsg.Start(); GridPrintingTitle.Visibility = Visibility.Collapsed; } private void Print_No_Code_Click(object sender, RoutedEventArgs e) { isHasCode = false; print(); } /// /// 窗体移动 /// /// /// /// /// private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DragMove(); } #region 摄像头 private int I = 9999; private bool IsRbnOpen = false; private List RbnOpen; private System.Timers.Timer times; /// /// 摄像头打开事件 /// /// /// /// /// private void RbnOpen_Click(object sender, RoutedEventArgs e) { if (!IsRbnOpen) { #region 防止连击 if (IsPressButton) { return; } else { IsPressButton = true; new Thread(new ThreadStart(new Action(() => { //Dispatcher.Invoke(new Action(() => { rbnTurnOff.IsEnabled = false; })); Thread.Sleep(500); //Dispatcher.Invoke(new Action(() => { rbnTurnOff.IsEnabled = true; })); IsPressButton = false; }))).Start(); } #endregion 防止连击 CameraHelper.UpdateCameraDevices(); if (CameraHelper.CameraDevices.Count > 0) { int CameraIndex = 0; for (int i = 0; i < CameraHelper.CameraDevices.Count; i++) { if (CameraHelper.CameraDevices[i].MonikerString == APP.CameraName) { CameraIndex = i; } } CameraHelper.SetCameraDevice(CameraIndex); RbnOpen = new List(); times = new System.Timers.Timer(200)//初始值为300 { AutoReset = true//设置是否执行System.Timers.Timer.Elapsed事件 };//设置执行一次(false)还是一直执行(true) times.Elapsed += new System.Timers.ElapsedEventHandler(Times_Elapsed); times.Enabled = true; //启动计时器 IsRbnOpen = true; string imgPath = FileToolsCommon.GetFileAbsolutePath("Temp/imgplayer"); FileToolsCommon.CreateDirectory(imgPath); } } } /// /// 摄像头关闭事件 /// /// /// /// /// private void RbnTurnOff_Click(object sender, RoutedEventArgs e) { if (IsRbnOpen) { #region 防止连击 if (IsPressButton) { return; } else { IsPressButton = true; new Thread(new ThreadStart(new Action(() => { //Dispatcher.Invoke(new Action(() => { rbnOpen.IsEnabled = false; })); Thread.Sleep(500); //Dispatcher.Invoke(new Action(() => { rbnOpen.IsEnabled = true; })); IsPressButton = false; }))).Start(); } #endregion 防止连击 IsRbnOpen = false; imgPlayerRight.Visibility = Visibility.Collapsed; imgPlayerLeft.Visibility = Visibility.Collapsed; imgPlayerRightUnder.Visibility = Visibility.Collapsed; imgPlayerLeftUnder.Visibility = Visibility.Collapsed; CameraHelper.CloseDevice(); I = 9999; } } private void Times_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (IsRbnOpen) { try { Dispatcher.Invoke(() => { if (I > 10010) { long time = Timestamp(); string imgPath = FileToolsCommon.GetFileAbsolutePath("Temp/imgplayer"); //string FilePathName = ImgPath + RsImgName.Count + ".png"; string path = CameraHelper.CaptureImage(imgPath, time.ToString()); if (!string.IsNullOrWhiteSpace(path)) { RbnOpen.Add(path); imgPlayerRight.Visibility = Visibility.Visible; /// < !--摄像头位置 1.右上 2.左上 3.右下 4.左下-- > if ("1".Equals(APP.CameraPosition)) { imgPlayerRight.Visibility = Visibility.Visible; imgPlayerLeft.Visibility = Visibility.Collapsed; imgPlayerRightUnder.Visibility = Visibility.Collapsed; imgPlayerLeftUnder.Visibility = Visibility.Collapsed; imgPlayerRight.Source = new BitmapImage(new Uri(path)); } else if ("2".Equals(APP.CameraPosition)) { imgPlayerRight.Visibility = Visibility.Collapsed; imgPlayerLeft.Visibility = Visibility.Visible; imgPlayerRightUnder.Visibility = Visibility.Collapsed; imgPlayerLeftUnder.Visibility = Visibility.Collapsed; imgPlayerLeft.Source = new BitmapImage(new Uri(path)); } else if ("3".Equals(APP.CameraPosition)) { imgPlayerRight.Visibility = Visibility.Collapsed; imgPlayerLeft.Visibility = Visibility.Collapsed; imgPlayerRightUnder.Visibility = Visibility.Visible; imgPlayerLeftUnder.Visibility = Visibility.Collapsed; imgPlayerRightUnder.Source = new BitmapImage(new Uri(path)); } else if ("4".Equals(APP.CameraPosition)) { imgPlayerRight.Visibility = Visibility.Collapsed; imgPlayerLeft.Visibility = Visibility.Collapsed; imgPlayerRightUnder.Visibility = Visibility.Collapsed; imgPlayerLeftUnder.Visibility = Visibility.Visible; imgPlayerLeftUnder.Source = new BitmapImage(new Uri(path)); } else { imgPlayerLeft.Visibility = Visibility.Collapsed; imgPlayerRightUnder.Visibility = Visibility.Collapsed; imgPlayerLeftUnder.Visibility = Visibility.Collapsed; imgPlayerRight.Source = new BitmapImage(new Uri(path)); } } } I++; }); } catch (Exception ex) { LogHelper.WriteErrLog("【摄像】(Times_Elapsed)生成图片错误:" + ex.Message, ex); } } } #endregion 摄像头 #region 设备检测 /// /// 设备检测 /// /// /// /// /// private void BtnDevice_Click(object sender, RoutedEventArgs e) { rbnTurnOff.IsChecked = true; RbnTurnOff_Click(null, null); DeviceWindow deviceWin = new DeviceWindow(); deviceWin.Show(); } #endregion 设备检测 #endregion 事件 #region 画笔 /// /// 画笔颜色事件 蓝色 /// /// /// /// /// private void BtnBlue_Click(object sender, RoutedEventArgs e) { drawingAttributes.Color = Colors.DeepSkyBlue; Color = Colors.DeepSkyBlue; imgRed.Visibility = Visibility.Collapsed; imgGray.Visibility = Visibility.Collapsed; imgCyanBlue.Visibility = Visibility.Collapsed; imgYellow.Visibility = Visibility.Collapsed; imgBlue.Visibility = Visibility.Visible; } /// /// 画笔颜色事件 青色 /// /// /// /// /// private void BtnCyanBlue_Click(object sender, RoutedEventArgs e) { drawingAttributes.Color = Colors.LimeGreen; Color = Colors.LimeGreen; imgRed.Visibility = Visibility.Collapsed; imgGray.Visibility = Visibility.Collapsed; imgCyanBlue.Visibility = Visibility.Visible; imgYellow.Visibility = Visibility.Collapsed; imgBlue.Visibility = Visibility.Collapsed; } /// /// 画笔颜色事件 黑色 /// /// /// /// /// private void BtnGray_Click(object sender, RoutedEventArgs e) { drawingAttributes.Color = Colors.Black; Color = Colors.Black; imgRed.Visibility = Visibility.Collapsed; imgGray.Visibility = Visibility.Visible; imgCyanBlue.Visibility = Visibility.Collapsed; imgYellow.Visibility = Visibility.Collapsed; imgBlue.Visibility = Visibility.Collapsed; } /// /// 画笔颜色事件 红色 /// /// /// /// /// private void BtnRed_Click(object sender, RoutedEventArgs e) { //设置 DrawingAttributes 的 Color 属性设置颜色 drawingAttributes.Color = Colors.Red; Color = Colors.Red; imgRed.Visibility = Visibility.Visible; imgGray.Visibility = Visibility.Collapsed; imgCyanBlue.Visibility = Visibility.Collapsed; imgYellow.Visibility = Visibility.Collapsed; imgBlue.Visibility = Visibility.Collapsed; } /// /// 画笔颜色事件 白色 /// /// /// /// /// private void BtnWhite_Click(object sender, RoutedEventArgs e) { ////创建 DrawingAttributes 类的一个实例 //drawingAttributes = new DrawingAttributes(); ////将 InkCanvas 的 DefaultDrawingAttributes 属性的值赋成创建的 DrawingAttributes 类的对象的引用 ////InkCanvas 通过 DefaultDrawingAttributes 属性来获取墨迹的各种设置,该属性的类型为 DrawingAttributes 型 //blackboard_canvas.DefaultDrawingAttributes = drawingAttributes; ////设置 DrawingAttributes 的 Color 属性设置颜色 drawingAttributes.Color = Colors.White; Color = Colors.White; } /// /// 画笔颜色事件 黄色 /// /// /// /// /// private void BtnYellow_Click(object sender, RoutedEventArgs e) { drawingAttributes.Color = Colors.Gold; Color = Colors.Gold; imgRed.Visibility = Visibility.Collapsed; imgGray.Visibility = Visibility.Collapsed; imgCyanBlue.Visibility = Visibility.Collapsed; imgYellow.Visibility = Visibility.Visible; imgBlue.Visibility = Visibility.Collapsed; } private void imgCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { mouseDown = true; imageOperationUtil.setMouseDown(mouseDown); } /// /// 画笔粗细事件 粗 /// /// /// /// /// private void RbnCrude_Click(object sender, RoutedEventArgs e) { drawingAttributes.Width = 5; drawingAttributes.Height = 5; PenSize = 5; } /// /// 画笔粗细事件 细 /// /// /// /// /// private void RbnFine_Click(object sender, RoutedEventArgs e) { drawingAttributes.Width = 1; drawingAttributes.Height = 1; PenSize = 1; } /// /// 画笔粗细事件 中 /// /// /// /// /// private void RbnIn_Click(object sender, RoutedEventArgs e) { drawingAttributes.Width = 3; drawingAttributes.Height = 3; PenSize = 3; } #endregion 画笔 #region 导入截图 /// /// 防止图片地址重复 /// private long WordImgNum = 9999; /// /// 返回一个时间戳到毫秒 /// /// /// public static long Timestamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); long timestr = Convert.ToInt64(ts.TotalMilliseconds); return timestr; } /// /// 获取时间戳 /// /// /// public string GetTimeStamp() { TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } /// /// 导入-结束 /// /// /// public void InvokeServerCompate(object obj) { //APP.myloading.Hide(); APP.myloading.Hide(); } public void WindowType() { this.Activate(); } /// /// 导入事件 /// /// /// /// /// private void BtnImport_Click(object sender, RoutedEventArgs e) { try { Record(); HideAngleBorder(); string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); ofd = new System.Windows.Forms.OpenFileDialog { //Filter = "文档|*.docx;*.doc;*.ppt;*.pptx", //增加导入图片 Filter = "文档|*.docx;*.doc;*.ppt;*.pptx;*.pdf|图片|*.jpg;*.jpeg;*.png;*.bmp", InitialDirectory = desktopPath, Multiselect = false, AddExtension = true, DereferenceLinks = true }; APP.BackgroundWorkerHelper.RunWorkerAsync(InvokeServering, InvokeServerCompate); } catch (Exception ex) { LogHelper.WriteErrLog("【导入(BtnImport_Click)" + ex.Message, ex); } } /// /// 截图事件 /// /// /// /// /// private void BtnScreenshot_Click(object sender, RoutedEventArgs e) { double do1 = GridContent.ActualHeight; double dou = GridMain.ActualHeight; Record(); HideAngleBorder(); imgCanvas.Margin = new Thickness(0, 0, 0, 0); APP.ImgPath = string.Empty; string time = GetTimeStamp(); string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + time + ".jpg"; APP.ImgPath = desktopPath; ImageHelper.GetScreenshot(new System.Drawing.Rectangle(0, 0, 0, 0), desktopPath, false, out BitmapImage bitmap); k_hook.Stop(); if (WindowState == WindowState.Normal)//截图隐藏窗口 { WindowState = WindowState.Minimized; } if (APP.W_JieTuWindow != null) { APP.W_JieTuWindow.initialization(); APP.W_JieTuWindow.Screenshot(); APP.W_JieTuWindow.InitializeKeyDownEvent(); APP.W_JieTuWindow.WindowState = WindowState.Maximized; APP.W_JieTuWindow.Visibility = Visibility.Visible; } else { APP.W_JieTuWindow = new JieTuWindow(); APP.W_JieTuWindow.InitializeKeyDownEvent(); // 订阅事件 APP.W_JieTuWindow.ChangeTextEvent += new ChangeTextHandler(frm_ChangeTextEvent); APP.W_JieTuWindow.click_closeJietuWindowClick += JietuWindow_click_closeJietuWindowClick; APP.W_JieTuWindow.Show(); } } /// /// 截图关闭窗口 /// /// /// private void frm_ChangeTextEvent(string text) { if ("关闭窗口".Equals(text)) { if (WindowState == WindowState.Minimized)//截图完恢复窗口 { WindowState = WindowState.Normal; Activate(); } InitializeKeyDownEvent(); if (!string.IsNullOrWhiteSpace(APP.ImgPath) && File.Exists(APP.ImgPath)) { if (APP.PageContextData.currpage == 0) { APP.PageContextData.pagenum += 1; APP.PageContextData.currpage = APP.PageContextData.pagenum; myblackboard.changepage(APP.PageContextData.currpage - 1); GridPage.Visibility = Visibility.Visible;//页码大于0 显示 #region 插入页码 PageData = new List(); for (int i = 1; i <= APP.PageContextData.pagenum; i++) { PageData pd = new PageData(); pd.PageName = i.ToString();// + "页"; pd.PageCode = i; PageData.Add(pd); } #endregion 插入页码 } if (APP.PageDrawList.Count >= APP.PageContextData.currpage) { APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath = APP.ImgPath;//zxycs APP.PageDrawList[APP.PageContextData.currpage - 1].PdfImagePath = APP.ImgPath; } else { Model_DrawData model_DrawData = new Model_DrawData { PageImagePath = APP.ImgPath, PdfImagePath = APP.ImgPath }; APP.PageDrawList.Add(model_DrawData); } if (APP.PageDrawList.Count >= APP.PageContextData.currpage && !string.IsNullOrWhiteSpace(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath)) { imgDocumentation.Source = null; BitmapImage bitImg = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath)); mouseDown = false; imageOperationUtil.setMouseDown(mouseDown); APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation = new TranslateTransform { X = 0.1, Y = 0.1 }; APP.PageDrawList[APP.PageContextData.currpage - 1].Type = "截图"; APP.PageDrawList[APP.PageContextData.currpage - 1].IsImageLocation = false; imgCanvas.Source = bitImg; imgCanvas.Width = bitImg.Width; imgCanvas.Height = bitImg.Height; ScroMain.ScrollToVerticalOffset(0); APP.PageDrawList[APP.PageContextData.currpage - 1].ImageSizes = new ScaleTransform { CenterX = imgCanvas.Width, CenterY = imgCanvas.Height }; BtnPrint.IsEnabled = true; } } } else if ("取消".Equals(text)) { if (WindowState == WindowState.Minimized)//截图完恢复窗口 { WindowState = WindowState.Normal; } } } /// 截图的图片鼠标右键事件 private void imgCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { imgCanvas.Source = null; APP.PageDrawList[APP.PageContextData.currpage - 1].PdfImagePath = null; APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath = null; } /// /// 导入-开始 /// /// /// private object InvokeServering() { Dispatcher.Invoke(new Action(() => { result = ofd.ShowDialog(); })); if (result == System.Windows.Forms.DialogResult.OK) { if (ofd.FileName != "") { List imagelist = new List() { "jpg", "jpeg", "png", "bmp" }; Dispatcher.Invoke(new Action(() => { APP.myloading.Show(); myblackboard.changepage(APP.PageContextData.pagenum); })); string filepath = ofd.FileName; string filesuff = filepath.Substring(filepath.LastIndexOf(".") + 1).ToLower(); string path = ofd.SafeFileName.Replace(".ppt", "").Replace(".pptx", "").Trim(); string type = ofd.SafeFileName.Replace(".ppt", "typezsygppt").Replace(".pptx", "typezsygppt").Replace(".pdf", "typepdf").Trim(); if (type.Contains("typezsygppt"))//ppt { try { #region PPT转PDF string pathTemp = AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; path = pathTemp + path + ".pdf"; FileToolsCommon.CreateDirectory(pathTemp); //PPT转PDF Presentation ppt = new Presentation(filepath); ppt.Save(path, Aspose.Slides.Export.SaveFormat.Pdf); #endregion PPT转PDF #region PDF转图片 // 图片绝对路径集合 List images = new List(); string directoryPath = pathTemp; //定义Jpeg转换设备 Aspose.Pdf.Document document = new Aspose.Pdf.Document(path); Aspose.Pdf.Devices.JpegDevice device = new Aspose.Pdf.Devices.JpegDevice(); //int quality = int.Parse(this.comboBox1.SelectedItem.ToString()); //directoryPath += quality; Directory.CreateDirectory(directoryPath); //默认质量为100,设置质量的好坏与处理速度不成正比,甚至是设置的质量越低反而花的时间越长,怀疑处理过程是先生成高质量的再压缩 device = new Aspose.Pdf.Devices.JpegDevice(100); //遍历每一页转为jpg for (int i = 1; i <= document.Pages.Count; i++) { long ii = Timestamp(); string filePathOutPut = Path.Combine(directoryPath, string.Format("{0}{1}.jpg", ii, i)); images.Add(filePathOutPut); FileStream fs = new FileStream(filePathOutPut, FileMode.OpenOrCreate); try { device.Process(document.Pages[i], fs); fs.Close(); } catch (Exception) { fs.Close(); File.Delete(filePathOutPut); } } #endregion PDF转图片 Dispatcher.Invoke(new Action(() => { string[] page = images.ToArray(); int num = 0; int iStart = APP.PageContextData.pagenum;//导入文档的开始下标 int iEnd = page.Length + APP.PageContextData.pagenum;//导入文档的结束下标 for (int i = 0 + APP.PageContextData.pagenum; i < page.Length + APP.PageContextData.pagenum; i++)//给画板模型加图片路径 { if (APP.PageDrawList != null && APP.PageDrawList.Count > i) { APP.PageDrawList[i].PageImagePath = page[i - APP.PageContextData.pagenum]; //zxycs APP.PageDrawList[i].PdfImagePath = page[i - APP.PageContextData.pagenum]; APP.PageDrawList[i].PageNum = i + 1; APP.PageDrawList[i].ImgDocumentation = true; APP.PageDrawList[i].Type = "ppt"; } else { Model_DrawData model_DrawData = new Model_DrawData { PageImagePath = page[i - APP.PageContextData.pagenum], PdfImagePath = page[i - APP.PageContextData.pagenum], PageNum = i + 1, ImgDocumentation = true, Type = "ppt" }; APP.PageDrawList.Add(model_DrawData); } BtnPrint.IsEnabled = true; APP.SaveDraw(); num++; } if (num > 0) { APP.PageContextData.currpage = APP.PageContextData.pagenum + 1; APP.PageContextData.pagenum += num; GridPage.Visibility = Visibility.Visible;//页码大于0 显示 } if (APP.PageContextData.currpage > 0 && APP.PageContextData.currpage <= APP.PageDrawList.Count) { imgCanvas.Source = null; BtnScreenshot.IsEnabled = false; imgDocumentation.Source = null; imgPPT.Source = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath)); ScroMain.ScrollToVerticalOffset(0); for (int i = iStart; i < iEnd; i++) { APP.PageDrawList[i].ImageLocation = new TranslateTransform { X = 0.1, Y = 0.1 }; APP.PageDrawList[i].IsImageLocation = true; APP.PageDrawList[i].ImageSizes = new ScaleTransform { CenterX = imgCanvas.Width, CenterY = imgCanvas.Height }; } } else { imgDocumentation.Source = null; imgCanvas.Source = null; imgPPT.Source = null; ///截图可用 BtnScreenshot.IsEnabled = true; } })); } catch (Exception ex) { Dispatcher.Invoke(new Action(() => { MessageWindow.Show("无法访问文件,请检查文件是否有效或解除文件占用!"); })); LogHelper.WriteErrLog("【打开ppt】(OpenDialog PPT)" + ex.Message, ex); } } else if (type.Contains("typepdf")) { try { string pathTemp = AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; #region PDF转图片 // 图片绝对路径集合 List images = new List(); string directoryPath = pathTemp; //aspose许可证 //Aspose.Pdf.License l = new Aspose.Pdf.License(); //string licenseName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Aspose.Total.Product.Family.lic"); //l.SetLicense(licenseName); //定义Jpeg转换设备 Aspose.Pdf.Document document = new Aspose.Pdf.Document(filepath); Aspose.Pdf.Devices.JpegDevice device = new Aspose.Pdf.Devices.JpegDevice(); //int quality = int.Parse(this.comboBox1.SelectedItem.ToString()); //directoryPath += quality; Directory.CreateDirectory(directoryPath); //默认质量为100,设置质量的好坏与处理速度不成正比,甚至是设置的质量越低反而花的时间越长,怀疑处理过程是先生成高质量的再压缩 device = new Aspose.Pdf.Devices.JpegDevice(100); //遍历每一页转为jpg for (int i = 1; i <= document.Pages.Count; i++) { long ii = Timestamp(); string filePathOutPut = Path.Combine(directoryPath, string.Format("{0}{1}.jpg", ii, i)); images.Add(filePathOutPut); FileStream fs = new FileStream(filePathOutPut, FileMode.OpenOrCreate); try { device.Process(document.Pages[i], fs); fs.Close(); } catch (Exception) { fs.Close(); File.Delete(filePathOutPut); } } #endregion PDF转图片 string[] page = images.ToArray(); int num = 0; int iStart = APP.PageContextData.pagenum;//导入文档的开始下标 int iEnd = page.Length + APP.PageContextData.pagenum;//导入文档的结束下标 Dispatcher.Invoke(new Action(() => { for (int i = APP.PageContextData.pagenum; i < page.Length + APP.PageContextData.pagenum; i++)//给画板模型加图片路径 { if (APP.PageDrawList != null && APP.PageDrawList.Count > i) { APP.PageDrawList[i].PageImagePath = page[i - APP.PageContextData.pagenum]; //zxycs APP.PageDrawList[i].PdfImagePath = page[i - APP.PageContextData.pagenum]; APP.PageDrawList[i].PageNum = i + 1; APP.PageDrawList[i].ImgDocumentation = true; APP.PageDrawList[i].Type = "word"; } else { Model_DrawData model_DrawData = new Model_DrawData { PageImagePath = page[i - APP.PageContextData.pagenum], PdfImagePath = page[i - APP.PageContextData.pagenum], PageNum = i + 1, ImgDocumentation = true, Type = "word" }; APP.PageDrawList.Add(model_DrawData); } BtnPrint.IsEnabled = true; APP.SaveDraw(); num++; } if (num > 0) { APP.PageContextData.currpage = APP.PageContextData.pagenum + 1; APP.PageContextData.pagenum += num; GridPage.Visibility = Visibility.Visible;//页码大于0 显示 } if (APP.PageContextData.currpage > 0 && APP.PageContextData.currpage <= APP.PageDrawList.Count) { imgCanvas.Source = null; imgPPT.Source = null; BtnScreenshot.IsEnabled = false; imgDocumentation.Visibility = Visibility.Visible; imgDocumentation.Source = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath));//给当前页面展示图片 ScroMain.ScrollToVerticalOffset(0); } else { imgDocumentation.Source = null; imgCanvas.Source = null; imgPPT.Source = null; ///截图可用 BtnScreenshot.IsEnabled = true; } })); } catch (Exception ex) { Dispatcher.Invoke(new Action(() => { MessageWindow.Show(ex.Message); })); LogHelper.WriteErrLog("【打开pdf】(OpenDialog pdf)" + ex.Message, ex); } } else if (imagelist.Contains(filesuff))///导入图片 { string imagepath = AppDomain.CurrentDomain.BaseDirectory + "temp"; if (!Directory.Exists(imagepath)) { Directory.CreateDirectory(imagepath); } TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); string timestr = Convert.ToInt64(ts.TotalMilliseconds).ToString(); string filepathCopy = Path.Combine(imagepath, timestr + ofd.SafeFileName); System.IO.File.Copy(filepath, filepathCopy); filepath = filepathCopy; APP.ImgPath = filepath; Dispatcher.Invoke(new Action(() => { if (APP.PageContextData.currpage == 0) { APP.PageContextData.pagenum += 1; APP.PageContextData.currpage = APP.PageContextData.pagenum; myblackboard.changepage(APP.PageContextData.currpage - 1); GridPage.Visibility = Visibility.Visible;//页码大于0 显示 #region 插入页码 PageData = new List(); for (int i = 1; i <= APP.PageContextData.pagenum; i++) { PageData pd = new PageData(); pd.PageName = i.ToString();// + "页"; pd.PageCode = i; PageData.Add(pd); } #endregion 插入页码 } else { APP.PageContextData.pagenum += 1; APP.PageContextData.currpage = APP.PageContextData.pagenum; myblackboard.changepage(APP.PageContextData.currpage - 1); } if (APP.PageDrawList.Count >= APP.PageContextData.currpage) { APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath = APP.ImgPath;//zxycs APP.PageDrawList[APP.PageContextData.currpage - 1].PdfImagePath = APP.ImgPath; } else { Model_DrawData model_DrawData = new Model_DrawData { PageImagePath = APP.ImgPath, PdfImagePath = APP.ImgPath }; APP.PageDrawList.Add(model_DrawData); } if (APP.PageDrawList.Count >= APP.PageContextData.currpage && !string.IsNullOrWhiteSpace(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath)) { imgDocumentation.Source = null; BitmapImage bitImg = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath)); mouseDown = false; imageOperationUtil.setMouseDown(mouseDown); APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation = new TranslateTransform { X = 0.1, Y = 0.1 }; APP.PageDrawList[APP.PageContextData.currpage - 1].Type = "截图"; APP.PageDrawList[APP.PageContextData.currpage - 1].IsImageLocation = false; imgCanvas.Source = bitImg; imgCanvas.Width = bitImg.Width; imgCanvas.Height = bitImg.Height; ScroMain.ScrollToVerticalOffset(0); imgCanvas.Margin = new Thickness(APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation.X, APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation.Y, 0, 0); APP.PageDrawList[APP.PageContextData.currpage - 1].ImageSizes = new ScaleTransform { CenterX = imgCanvas.Width, CenterY = imgCanvas.Height }; BtnPrint.IsEnabled = true; } })); } else//word { try { string paths = AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; WordImgNum += 1; string[] page = ZAsposeUtil.ConvertWordToImage(filepath, paths, "" + WordImgNum, 0, 0).ToArray(); int num = 0; Dispatcher.Invoke(new Action(() => { for (int i = 0 + APP.PageContextData.pagenum; i < page.Length + APP.PageContextData.pagenum; i++)//给画板模型加图片路径 { if (APP.PageDrawList != null && APP.PageDrawList.Count > i) { APP.PageDrawList[i].PageImagePath = page[i - APP.PageContextData.pagenum]; //zxycs APP.PageDrawList[i].PdfImagePath = page[i - APP.PageContextData.pagenum]; APP.PageDrawList[i].PageNum = i + 1; APP.PageDrawList[i].ImgDocumentation = true; APP.PageDrawList[i].Type = "word"; } else { Model_DrawData model_DrawData = new Model_DrawData { PageImagePath = page[i - APP.PageContextData.pagenum], PdfImagePath = page[i - APP.PageContextData.pagenum], PageNum = i + 1, ImgDocumentation = true, Type = "word" }; APP.PageDrawList.Add(model_DrawData); } BtnPrint.IsEnabled = true; APP.SaveDraw(); num++; } if (num > 0) { APP.PageContextData.currpage = APP.PageContextData.pagenum + 1; APP.PageContextData.pagenum += num; GridPage.Visibility = Visibility.Visible;//页码大于0 显示 } if (APP.PageContextData.currpage > 0 && APP.PageContextData.currpage <= APP.PageDrawList.Count) { imgCanvas.Source = null; imgPPT.Source = null; BtnScreenshot.IsEnabled = false; imgDocumentation.Visibility = Visibility.Visible; imgDocumentation.Source = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath));//给当前页面展示图片 ScroMain.ScrollToVerticalOffset(0); } else { imgDocumentation.Source = null; imgCanvas.Source = null; imgPPT.Source = null; ///截图可用 BtnScreenshot.IsEnabled = true; } })); } catch (Exception ex) { Dispatcher.Invoke(new Action(() => { MessageWindow.Show("无法访问文件,请检查文件是否有效或解除文件占用!"); })); LogHelper.WriteErrLog("【XHMicroLessonSystemWindow】(OpenDialog 导入文档)" + ex.Message, ex); } } #region 插入页码 Dispatcher.Invoke(new Action(() => { PageData = new List(); for (int i = 1; i <= APP.PageContextData.pagenum; i++) { PageData pd = new PageData(); pd.PageName = i.ToString();//+ "页"; pd.PageCode = i; PageData.Add(pd); } })); #endregion 插入页码 } } //OpenDialog(); return ""; } /// /// 截图关闭 非正常关闭截图时,截图清空 /// private void JietuWindow_click_closeJietuWindowClick() { if (WindowState == WindowState.Minimized)//截图完恢复窗口 { WindowState = WindowState.Normal; } APP.W_JieTuWindow = null; } /// /// 导入文档 /// private void OpenDialog() { Dispatcher.Invoke(new Action(() => { result = ofd.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { if (ofd.FileName != "") { APP.myloading.Show(); myblackboard.changepage(APP.PageContextData.pagenum); #region PPT转PDF string filepath = ofd.FileName; string path = ofd.SafeFileName.Replace(".ppt", "").Replace(".pptx", "").Trim(); string type = ofd.SafeFileName.Replace(".ppt", "typezsygppt").Replace(".pptx", "typezsygppt").Replace(".pdf", "typepdf").Trim(); if (type.Contains("typezsygppt"))//ppt { try { string pathTemp = AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; path = pathTemp + path + ".pdf"; FileToolsCommon.CreateDirectory(pathTemp); //PPT转PDF Presentation ppt = new Presentation(filepath); ppt.Save(path, Aspose.Slides.Export.SaveFormat.Pdf); #endregion PPT转PDF #region PDF转图片 // 图片绝对路径集合 List images = new List(); string directoryPath = pathTemp; //aspose许可证 //Aspose.Pdf.License l = new Aspose.Pdf.License(); //string licenseName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Aspose.Total.Product.Family.lic"); //l.SetLicense(licenseName); //定义Jpeg转换设备 Aspose.Pdf.Document document = new Aspose.Pdf.Document(path); Aspose.Pdf.Devices.JpegDevice device = new Aspose.Pdf.Devices.JpegDevice(); //int quality = int.Parse(this.comboBox1.SelectedItem.ToString()); //directoryPath += quality; Directory.CreateDirectory(directoryPath); //默认质量为100,设置质量的好坏与处理速度不成正比,甚至是设置的质量越低反而花的时间越长,怀疑处理过程是先生成高质量的再压缩 device = new Aspose.Pdf.Devices.JpegDevice(100); //遍历每一页转为jpg for (int i = 1; i <= document.Pages.Count; i++) { long ii = Timestamp(); string filePathOutPut = Path.Combine(directoryPath, string.Format("{0}{1}.jpg", ii, i)); images.Add(filePathOutPut); FileStream fs = new FileStream(filePathOutPut, FileMode.OpenOrCreate); try { device.Process(document.Pages[i], fs); fs.Close(); } catch (Exception) { fs.Close(); File.Delete(filePathOutPut); } } #endregion PDF转图片 string[] page = images.ToArray(); int num = 0; for (int i = 0 + APP.PageContextData.pagenum; i < page.Length + APP.PageContextData.pagenum; i++)//给画板模型加图片路径 { if (APP.PageDrawList != null && APP.PageDrawList.Count > i) { APP.PageDrawList[i].PageImagePath = page[i - APP.PageContextData.pagenum]; //zxycs APP.PageDrawList[i].PdfImagePath = page[i - APP.PageContextData.pagenum]; APP.PageDrawList[i].PageNum = i + 1; APP.PageDrawList[i].ImgDocumentation = true; } else { Model_DrawData model_DrawData = new Model_DrawData { PageImagePath = page[i - APP.PageContextData.pagenum], PdfImagePath = page[i - APP.PageContextData.pagenum], PageNum = i + 1, ImgDocumentation = true }; APP.PageDrawList.Add(model_DrawData); } BtnPrint.IsEnabled = true; APP.SaveDraw(); num++; } if (num > 0) { APP.PageContextData.currpage = APP.PageContextData.pagenum + 1; APP.PageContextData.pagenum += num; GridPage.Visibility = Visibility.Visible;//页码大于0 显示 } if (APP.PageContextData.currpage > 0 && APP.PageContextData.currpage < APP.PageDrawList.Count) { imgCanvas.Source = null; BtnScreenshot.IsEnabled = false; imgDocumentation.Source = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath));//给当前页面展示图片 } else { imgDocumentation.Source = null; imgCanvas.Source = null; ///截图可用 BtnScreenshot.IsEnabled = true; } APP.myloading.Hide(); } catch (Exception ex) { APP.myloading.Hide(); MessageWindow.Show("无法访问文件,请检查文件是否有效或解除文件占用!"); LogHelper.WriteErrLog("【打开ppt】(OpenDialog PPT)" + ex.Message, ex); } } else if (type.Contains("typepdf")) { string pathTemp = AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; #region PDF转图片 // 图片绝对路径集合 List images = new List(); string directoryPath = pathTemp; //aspose许可证 //Aspose.Pdf.License l = new Aspose.Pdf.License(); //string licenseName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Aspose.Total.Product.Family.lic"); //l.SetLicense(licenseName); //定义Jpeg转换设备 Aspose.Pdf.Document document = new Aspose.Pdf.Document(filepath); Aspose.Pdf.Devices.JpegDevice device = new Aspose.Pdf.Devices.JpegDevice(); //int quality = int.Parse(this.comboBox1.SelectedItem.ToString()); //directoryPath += quality; Directory.CreateDirectory(directoryPath); //默认质量为100,设置质量的好坏与处理速度不成正比,甚至是设置的质量越低反而花的时间越长,怀疑处理过程是先生成高质量的再压缩 device = new Aspose.Pdf.Devices.JpegDevice(100); //遍历每一页转为jpg for (int i = 1; i <= document.Pages.Count; i++) { long ii = Timestamp(); string filePathOutPut = Path.Combine(directoryPath, string.Format("{0}{1}.jpg", ii, i)); images.Add(filePathOutPut); FileStream fs = new FileStream(filePathOutPut, FileMode.OpenOrCreate); try { device.Process(document.Pages[i], fs); fs.Close(); } catch (Exception) { fs.Close(); File.Delete(filePathOutPut); } } #endregion PDF转图片 string[] page = images.ToArray(); int num = 0; for (int i = 0 + APP.PageContextData.pagenum; i < page.Length + APP.PageContextData.pagenum; i++)//给画板模型加图片路径 { if (APP.PageDrawList != null && APP.PageDrawList.Count > i) { APP.PageDrawList[i].PageImagePath = page[i - APP.PageContextData.pagenum]; //zxycs APP.PageDrawList[i].PdfImagePath = page[i - APP.PageContextData.pagenum]; APP.PageDrawList[i].PageNum = i + 1; APP.PageDrawList[i].ImgDocumentation = true; } else { Model_DrawData model_DrawData = new Model_DrawData { PageImagePath = page[i - APP.PageContextData.pagenum], PdfImagePath = page[i - APP.PageContextData.pagenum], PageNum = i + 1, ImgDocumentation = true }; APP.PageDrawList.Add(model_DrawData); } BtnPrint.IsEnabled = true; APP.SaveDraw(); num++; } if (num > 0) { APP.PageContextData.currpage = APP.PageContextData.pagenum + 1; APP.PageContextData.pagenum += num; GridPage.Visibility = Visibility.Visible;//页码大于0 显示 } if (APP.PageContextData.currpage > 0 && APP.PageContextData.currpage < APP.PageDrawList.Count) { imgCanvas.Source = null; BtnScreenshot.IsEnabled = false; imgDocumentation.Source = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath));//给当前页面展示图片 } else { imgDocumentation.Source = null; imgCanvas.Source = null; ///截图可用 BtnScreenshot.IsEnabled = true; } APP.myloading.Hide(); } else//word { try { string paths = AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; WordImgNum += 1; string[] page = ZAsposeUtil.ConvertWordToImage(filepath, paths, "" + WordImgNum, 0, 0).ToArray(); int num = 0; for (int i = 0 + APP.PageContextData.pagenum; i < page.Length + APP.PageContextData.pagenum; i++)//给画板模型加图片路径 { if (APP.PageDrawList != null && APP.PageDrawList.Count > i) { APP.PageDrawList[i].PageImagePath = page[i - APP.PageContextData.pagenum]; //zxycs APP.PageDrawList[i].PdfImagePath = page[i - APP.PageContextData.pagenum]; APP.PageDrawList[i].PageNum = i + 1; APP.PageDrawList[i].ImgDocumentation = true; } else { Model_DrawData model_DrawData = new Model_DrawData { PageImagePath = page[i - APP.PageContextData.pagenum], PdfImagePath = page[i - APP.PageContextData.pagenum], PageNum = i + 1, ImgDocumentation = true }; APP.PageDrawList.Add(model_DrawData); } BtnPrint.IsEnabled = true; APP.SaveDraw(); num++; } if (num > 0) { APP.PageContextData.currpage = APP.PageContextData.pagenum + 1; APP.PageContextData.pagenum += num; GridPage.Visibility = Visibility.Visible;//页码大于0 显示 } if (APP.PageContextData.currpage > 0 && APP.PageContextData.currpage < APP.PageDrawList.Count) { imgCanvas.Source = null; BtnScreenshot.IsEnabled = false; imgDocumentation.Visibility = Visibility.Visible; imgDocumentation.Source = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath));//给当前页面展示图片 } else { imgDocumentation.Source = null; imgCanvas.Source = null; ///截图可用 BtnScreenshot.IsEnabled = true; } APP.myloading.Hide(); } catch (Exception ex) { APP.myloading.Hide(); LogHelper.WriteErrLog("【XHMicroLessonSystemWindow】(OpenDialog 导入文档)" + ex.Message, ex); } } } } } )); } #region 导入转换图片 /// /// 生成图片 /// /// /// 图片地址 /// /// /// 保存位置 /// /// /// 图片位置 /// /// /// 错误消息 /// /// /// private bool MergerImg(string _path, string _saveimg, RectangleF _rectangle, out string errmsg) { errmsg = null; try { Bitmap bitmap = null; //创建要显示的图片对象,根据参数的个数设置宽度 Bitmap backgroudImg = new Bitmap((int)GridM.ActualWidth, (int)GridM.ActualHeight); Graphics g = Graphics.FromImage(backgroudImg); //清除画布,背景设置为白色 g.Clear(System.Drawing.Color.White); if (!string.IsNullOrWhiteSpace(_path)) { bitmap = ImageHelper.ReadBitmapFile(_path); g.DrawImage(bitmap, _rectangle); } backgroudImg.Save(_saveimg); g.Dispose(); backgroudImg.Dispose(); if (bitmap != null) { bitmap.Dispose(); } GC.Collect(); return true; } catch (Exception ex) { errmsg = ex.Message; LogHelper.WriteErrLog("【截图合成】(MergerImg)图片合成失败:" + ex.Message, ex); return false; } } #endregion 导入转换图片 #endregion 导入截图 #region 上传 列表 /// /// 搜索集合匹配的索引 /// /// /// /// /// /// /// /// /// public static List FindChilds(DependencyObject parent, string childName) where T : DependencyObject { List list = new List(); if (parent == null) { return list; } int childrenCount = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < childrenCount; i++) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); // 如果子控件不是需查找的控件类型 T childType = child as T; if (childType == null) { // 在下一级控件中递归查找 List findChildList = FindChilds(child, childName); for (int j = 0; j < findChildList.Count; j++) { } list.AddRange(FindChilds(child, childName)); } else if (!string.IsNullOrEmpty(childName)) { FrameworkElement frameworkElement = child as FrameworkElement; // 如果控件名称符合参数条件 if (frameworkElement != null && frameworkElement.Name == childName) { list.Add((T)child); } } else { // 查找到了控件 list.Add((T)child); } } return list; } /// /// 加载视频列表 /// public void LoadingVideoList() { try { model_VideoList = new List(); foreach (Model_WKData Vdata in APP.WKDataList) { #region 计时器初始化 if (Vdata.VideoList == null) { continue; } foreach (Model_Video videoinfo in Vdata.VideoList) { try { if (string.IsNullOrWhiteSpace(videoinfo.VideoPath)) { continue; } if (string.IsNullOrWhiteSpace(videoinfo.VideoSize) || videoinfo.VideoSize == "0 MB") { videoinfo.VideoSize = FileToolsCommon.GetFileSizeByMB(videoinfo.VideoPath).ToString() + " MB"; videoinfo.VideoSizebyte = FileToolsCommon.GetFileSize(videoinfo.VideoPath); } model_VideoList.Add(videoinfo); } catch (Exception ex) { LogHelper.WriteErrLog("【加载视频列表】(LoadingVideoList)" + ex.Message, ex); } } #endregion 计时器初始化 } //翻转 if (model_VideoList.Count > 1) { model_VideoList.Reverse(); } } catch (Exception ex) { LogHelper.WriteErrLog("【加载视频列表】(LoadingVideoList)" + ex.Message, ex); } } /// /// 上传事件 /// /// /// /// /// private void BtnUpload_Click(object sender, RoutedEventArgs e) { if (GridMyVideo.Visibility == Visibility.Visible) { GridMyVideo.Visibility = Visibility.Collapsed; GridMain.Visibility = Visibility.Visible; GridM.IsEnabled = true; GridRecordingTitle.Visibility = Visibility.Visible; } else { PageHide(); GridMyVideo.Visibility = Visibility.Visible; LoadUploadInitData(); } } #endregion 上传 列表 #region 新上传 显示缩略图 #region 初始值 private double ControlHeight = 260; private double ControlWidth = 250; /// /// 当前页 /// private int CurrentPage = 1; /// /// 横向间隔 /// private double IntervalX = 0; /// /// 纵向间隔 /// private double IntervalY = 0; /// /// 页面高 /// private double pageH; /// /// 每页显示的视频数 /// private int PageShowNum = 0; /// /// 页面宽 /// private double pageW; /// /// 总页数 /// private int TotalPage = 0; /// /// 视频信息列表 /// private List VideoControlList = new List(); #endregion 初始值 /// /// 加载当前页数据 /// private void LoadCurrentPageData() { lblVideoPageNum.Content = CurrentPage + "/" + TotalPage; //隐藏显示的控件 if (VideoControlList.Count > 0) { foreach (Uc_VideoItem item in VideoControlList) { if (item.Visibility != Visibility.Hidden) { item.Visibility = Visibility.Hidden; } } } double W = IntervalX;//每次增加250 double H = IntervalY;//每次增加260 //加载控件 for (int i = 0; i < PageShowNum; i++) { int DataIndex = (CurrentPage - 1) * PageShowNum + i; if (DataIndex == model_VideoList.Count) { return; } Uc_VideoItem videoItem; if (VideoControlList.Exists(x => x.Tag.ToString() == model_VideoList[DataIndex].FileGuid)) { videoItem = VideoControlList.Find(x => x.Tag.ToString() == model_VideoList[DataIndex].FileGuid); } else { if (!FileToolsCommon.IsExistFile(model_VideoList[DataIndex].ThumbnailPath)) { continue; } videoItem = new Uc_VideoItem(model_VideoList[DataIndex]) { Tag = model_VideoList[DataIndex].FileGuid }; videoItem.Click_refreshVideoList += LoadUploadInitData; videoItem.Click_UploadLogin += Login; videoItem.Width = ControlWidth; videoItem.Height = ControlHeight; videoItem.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; videoItem.VerticalAlignment = System.Windows.VerticalAlignment.Top; GridMyVideo.Children.Add(videoItem); VideoControlList.Add(videoItem); } videoItem.Margin = new Thickness(W, H, 0, 0); videoItem.Visibility = Visibility.Visible; if (W + ControlWidth + ControlWidth > pageW) { W = IntervalX; H += ControlHeight + IntervalY; } else { W += ControlWidth + IntervalX; } //Uc_VideoItem videoItem = new Uc_VideoItem(); //return; } } /// /// 初始化加载上传页面数据 /// private void LoadUploadInitData() { APP.myloading.Show(); //加载视频列表 LoadingVideoList(); if (model_VideoList.Count > 0) { lblVideoMess.Visibility = Visibility.Hidden; BtnVideoUpPage.Visibility = Visibility.Visible; lblVideoPageNum.Visibility = Visibility.Visible; BtnVideoDownPage.Visibility = Visibility.Visible; if (GridMyVideo.ActualHeight > 0) { pageW = GridMyVideo.ActualWidth; pageH = GridMyVideo.ActualHeight; } else { pageW = GridRecordingArea.ActualWidth; pageH = GridRecordingArea.ActualHeight; } //获取设置控件大小 新增 页面原始1061 911 double PropWid = pageW / 1061.00; double PropHei = pageH / 911.00; //ControlWidth = 250.00 * PropWid; //ControlHeight = 260.00 * PropHei; //ControlWidth= //ControlHeight= //根据页面大小获取每页显示的数量 H260W250 int videoRow = (int)((pageH - 50) / ControlHeight); int videColumn = (int)(pageW / ControlWidth); //横向间隔 IntervalX = (pageW - (videColumn * ControlWidth)) / (videColumn + 1); IntervalY = (pageH - 50 - (videoRow * ControlHeight)) / (videoRow + 1); PageShowNum = (videoRow == 0 ? 1 : videoRow) * (videColumn == 0 ? 1 : videColumn); //获取总页数 TotalPage = model_VideoList.Count / PageShowNum + (model_VideoList.Count % PageShowNum > 0 ? 1 : 0); //如果当前页大于总页数 总页数为当前页 if (TotalPage < CurrentPage) { CurrentPage = TotalPage; } LoadCurrentPageData(); } else { lblVideoMess.Visibility = Visibility.Visible; BtnVideoUpPage.Visibility = Visibility.Hidden; lblVideoPageNum.Visibility = Visibility.Hidden; BtnVideoDownPage.Visibility = Visibility.Hidden; //隐藏显示的控件 if (VideoControlList.Count > 0) { foreach (Uc_VideoItem item in VideoControlList) { if (item.Visibility != Visibility.Hidden) { item.Visibility = Visibility.Hidden; } } } } APP.myloading.Hide(); } #region 分页 /// /// 下一页 /// /// /// /// /// private void BtnVideoDownPage_Click(object sender, RoutedEventArgs e) { if (CurrentPage < TotalPage) { CurrentPage++; LoadCurrentPageData(); } } /// /// 上一页 /// /// /// /// /// private void BtnVideoUpPage_Click(object sender, RoutedEventArgs e) { if (CurrentPage > 1) { CurrentPage--; LoadCurrentPageData(); } } #endregion 分页 #endregion 新上传 显示缩略图 #region 录屏 /// /// 录屏事件 /// /// /// /// /// private void BtnScreenRecording_Click(object sender, RoutedEventArgs e) { luoBoPenUtil.lb_device_mouse(); if (!microphoneGood) { MessageWindow.Show("麦克风不可用"); return; } if (!loudspeakerGood) { MessageWindow.Show("扬声器不可用"); return; } Record(); k_hook.Stop(); if (APP.W_ScreenRecordingToolbarWindow == null) { APP.W_ScreenRecordingToolbarWindow = new ScreenRecordingToolbarWindow { Topmost = true }; APP.W_ScreenRecordingToolbarWindow.Initialize(); } else { APP.W_ScreenRecordingToolbarWindow.Initialize(); } APP.W_ScreenRecordingToolbarWindow.Click_stopRecordingScreen += W_ScreenRecordingToolbarWindow_Click_stopRecordingScreen; //显示在右下角 APP.W_ScreenRecordingToolbarWindow.WindowStartupLocation = WindowStartupLocation.Manual; Graphics graphics = Graphics.FromHwnd(IntPtr.Zero); float DIP = graphics.DpiX; float DIPY = graphics.DpiY; APP.W_ScreenRecordingToolbarWindow.Left = PrimaryScreen.WorkingArea.Width / (DIP / 96) - APP.W_ScreenRecordingToolbarWindow.Width; APP.W_ScreenRecordingToolbarWindow.Top = PrimaryScreen.WorkingArea.Height / (DIP / 96) - APP.W_ScreenRecordingToolbarWindow.Height - 100; APP.W_ScreenRecordingToolbarWindow.Topmost = true; APP.W_ScreenRecordingToolbarWindow.Show(); Hide(); } /// /// 保存录屏中 /// private void W_ScreenRecordingToolbarWindow_Click_stopRecordingScreen() { TxbTime.Text = "00:00"; TxbType.Text = "保存中"; RecordType = 1; BtnScreenRecording.IsEnabled = false; new Thread(new ThreadStart(new Action(() => { while (FileToolsCommon.IsExistDirectory(APP.WKData.WkPath + "_temppath/")) { Thread.Sleep(100); } Thread.Sleep(100); Dispatcher.Invoke(() => { RecordType = 0; BtnScreenRecording.IsEnabled = true; TxbType.Text = "准备就绪"; }); }))).Start(); } #endregion 录屏 #region 录制窗口 #region 变量 /// /// 录制大小 /// private int gridActHeight = 898; /// /// 录制大小 /// private int gridActWidth = 1276; /// /// 录制类型 0停止中,1录制中,2暂停中 3倒计时 /// private int RecordType = 0; /// /// 录制计时 /// private DateTime SRTime = DateTime.Now; /// /// 音频保存路径名 /// private string TempAudioPathName; /// /// 视频合成前路径名 /// private string TempVideoPathName; /// /// 截图定时器 /// private System.Threading.Timer timer; /// /// 视频保存路径名 /// private string VideoSavePathName; #endregion 变量 private bool IsPressButton = false; /// /// 记录上次截图时间 /// private DateTime Recorddt = DateTime.Now; //视频写入 private VideoFileWriter videoWriter = new VideoFileWriter(); //录制麦克风的声音 private WaveInEvent waveIn = null; private bool waveIn_runing = false; //音频写入 private WaveFileWriter writer = null; /// /// 录制窗口内容 /// /// /// /// /// private async void BtnRecord_Click(object sender, RoutedEventArgs e) { #region 防止连击 if (IsPressButton) { return; } else { IsPressButton = true; new Thread(new ThreadStart(new Action(() => { Thread.Sleep(500); IsPressButton = false; }))).Start(); } #endregion 防止连击 if (APP.PageContextData.currpage == 0) { MessageWindow.Show("请先导入文档或截图!"); return; } if (RecordType == 0) { start_pause_grid.Visibility = Visibility.Hidden; stop_grid.Visibility = Visibility.Hidden; close_grid.Visibility = Visibility.Hidden; if (!microphoneGood) { start_pause_grid.Visibility = Visibility.Visible; stop_grid.Visibility = Visibility.Visible; close_grid.Visibility = Visibility.Visible; MessageWindow.Show("麦克风不可用"); return; } blackboard_canvas.Visibility = Visibility.Visible; if (RectImgBorder.Visibility != Visibility.Hidden) { HideAngleBorder(); } Record(); BtnPrint.IsEnabled = false; BtnScreenshot.IsEnabled = false; BtnImport.IsEnabled = false; BtnScreenRecording.IsEnabled = false; BtnUpload.IsEnabled = false; BtnSetUp.IsEnabled = false; BtnDevice.IsEnabled = false; BtnLoginType.IsEnabled = false; blackboard_canvas.Visibility = Visibility.Visible; TxbType.Text = "准备录制"; BtnRecord.Visibility = Visibility.Collapsed; BtnRecordSuspend.Visibility = Visibility.Visible; BtnRecord.IsEnabled = true; BtnStop.IsEnabled = true; #region 录像倒计时 if (APP.W_CountdownWindow == null) { APP.W_CountdownWindow = new CountdownWindow(); APP.W_CountdownWindow.Initialize(); } else { APP.W_CountdownWindow.Initialize(); } APP.W_CountdownWindow.Show(); #endregion 录像倒计时 await Task.Delay(3000); //停止中开始录制 RecordType = 3; close_grid.Visibility = Visibility.Visible; TxbType.Text = "正在录制"; RecordType = 1; await StartRecord(); start_pause_grid.Visibility = Visibility.Visible; stop_grid.Visibility = Visibility.Visible; } else if (RecordType == 1) { //录制中暂停 RecordType = 2; } else if (RecordType == 2) { //暂停中继续录制 RecordType = 1; } if (RecordType == 0) { TxbType.Text = "准备录制"; BtnRecord.Visibility = Visibility.Visible; BtnRecordSuspend.Visibility = Visibility.Collapsed; BtnRecord.IsEnabled = true; BtnStop.IsEnabled = false; } else if (RecordType == 1) { TxbType.Text = "录制中"; BtnRecord.Visibility = Visibility.Collapsed; BtnRecordSuspend.Visibility = Visibility.Visible; } else if (RecordType == 2) { TxbType.Text = "暂停中"; BtnRecord.Visibility = Visibility.Visible; BtnRecordSuspend.Visibility = Visibility.Collapsed; } else if (RecordType == 3) { TxbType.Text = "倒计时"; } } /// /// 停止录制窗口内容 /// /// /// /// /// private async void BtnStop_Click(object sender, RoutedEventArgs e) { #region 防止连击 if (IsPressButton) { return; } else { IsPressButton = true; new Thread(new ThreadStart(new Action(() => { Thread.Sleep(500); IsPressButton = false; }))).Start(); } #endregion 防止连击 if (RecordType != 0) { blackboard_canvas.Visibility = Visibility.Collapsed; //鼠标模式 luoBoPenUtil.lb_device_mouse(); await EndRecord(); RecordType = 0; } } /// /// 停止录制并生成录制文件 /// private async Task EndRecord() { #region 恢复被禁用的按钮 BtnScreenshot.IsEnabled = true; BtnImport.IsEnabled = true; BtnScreenRecording.IsEnabled = true; BtnUpload.IsEnabled = true; BtnSetUp.IsEnabled = true; BtnDevice.IsEnabled = true; BtnLoginType.IsEnabled = true; #endregion 恢复被禁用的按钮 APP.PageContextData.currpage = 0; APP.PageContextData.pagenum = 0; myblackboard.clear(); APP.PageDrawList.Clear(); imgCanvas.Source = null; imgDocumentation.Source = null; imgPPT.Source = null; GridPage.Visibility = Visibility.Collapsed; BtnRecord.IsEnabled = false; BtnStop.IsEnabled = false; BtnScreenRecording.IsEnabled = false; timer.Change(-1, 0); timer.Dispose(); TxbTime.Text = "00:00"; TxbType.Text = "保存中"; start_pause_grid.Visibility = Visibility.Hidden; await Task.Run(() => { try { videoWriter.Close(); waveIn.StopRecording(); //等待音频结束回调 while (waveIn_runing) { Thread.Sleep(300); } Process[] KillProcessArray = Process.GetProcessesByName("ffmpeg"); foreach (Process KillProcess in KillProcessArray) { KillProcess.Kill(); } FFMpegConverter ffMpeg = new FFMpegConverter(); FFMpegInput[] input = new FFMpegInput[] { new FFMpegInput(TempVideoPathName), new FFMpegInput(TempAudioPathName) }; // 音视频合并 ffMpeg.ConvertMedia( input, VideoSavePathName, "mp4", new OutputSettings() { } ); //生成缩略图 string ThumbnailPath = FileToolsCommon.GetDirectoryName(VideoSavePathName) + "ThumbnailPath/"; FileToolsCommon.CreateDirectory(ThumbnailPath); //缩略图存储位置 string ThumbnailPathName = ThumbnailPath + FileToolsCommon.GetIOFileName(VideoSavePathName).Replace(".", "") + ".JPG"; FileToolsCommon.DeleteFile(ThumbnailPathName); VideoInfo.RSTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); VideoInfo.VideoPath = VideoSavePathName; VideoInfo.ThumbnailPath = ThumbnailPathName; VideoInfo.FileGuid = Guid.NewGuid().ToString(); VideoInfo.IsUpload = false; VideoInfo.Uploaded = 0; try { bool ThuRes = APP.FFmpeg.GenerateThumbnails(TempVideoPathName, ThumbnailPathName, 200, 130); } catch (Exception ex) { LogHelper.WriteErrLog("录制生成缩略图", ex); } if (!APP.VideoList.Exists(x => x.FileGuid == VideoInfo.FileGuid) || !APP.VideoList.Exists(x => x.VideoPath == VideoInfo.VideoPath)) { APP.VideoList.Add(VideoInfo); //保存数据 APP.SaveWkData(); } try { FileToolsCommon.DeleteFile(TempVideoPathName); FileToolsCommon.DeleteFile(TempAudioPathName); } catch (Exception ex) { LogHelper.WriteErrLog("删除录制临时文件", ex); } } catch (Exception ex) { Dispatcher.Invoke(() => { MessageWindow.Show(ex.Message); }); } }); BtnRecord.IsEnabled = true; BtnStop.IsEnabled = false; BtnPrint.IsEnabled = false; BtnScreenRecording.IsEnabled = true; TxbType.Text = "准备就绪"; BtnRecord.Visibility = Visibility.Visible; BtnRecordSuspend.Visibility = Visibility.Collapsed; start_pause_grid.Visibility = Visibility.Visible; } /// /// 录制保存图片 /// private void RecordSaveImage() { try { //保存图片 try { Dispatcher.Invoke(() => { Bitmap bm = ImageHelper.SaveUI2Bitmap(GridMain, gridActWidth, gridActHeight); videoWriter.WriteVideoFrame(bm); bm.Dispose(); }); } catch (Exception e) { Console.WriteLine(e.Message); } } catch (Exception ex) { LogHelper.WriteErrLog("【录制】(Timer_Elapsed)生成图片错误:" + ex.Message, ex); } } //new WaveInEvent(); /// /// 开始录制和暂停录制 /// private async Task StartRecord() { await Task.Run(() => { //电子版切换笔模式 luoBoPenUtil.lb_device_hand(); VideoInfo = new Model_Video { VideoType = (Enum_VideoType)int.Parse(FileToolsCommon.GetConfigValue("VideoType")), WkType = Enum_WKVidetype.RecordingLessons }; FileToolsCommon.DeleteDirectory(APP.WKData.WkPath + "temp/"); FileToolsCommon.CreateDirectory(APP.WKData.WkPath); VideoSavePathName = APP.WKData.WkPath + APP.WKData.WkName + "_录制." + VideoInfo.VideoType.ToString(); TempVideoPathName = APP.WKData.WkPath + APP.WKData.WkName + "_录制Syn.avi"; int num = 1; while (FileToolsCommon.IsExistFile(VideoSavePathName)) { VideoSavePathName = APP.WKData.WkPath + APP.WKData.WkName + "_录制_" + num + "." + VideoInfo.VideoType.ToString(); TempVideoPathName = APP.WKData.WkPath + APP.WKData.WkName + "_录制Syn_" + num + ".avi"; num++; } TempAudioPathName = TempVideoPathName.Replace(".avi", ".mp3"); gridActWidth = (int)(GridMain.ActualWidth * (PrimaryScreen.DpiX / 96f) / 2) * 2; gridActHeight = (int)(GridMain.ActualHeight * (PrimaryScreen.DpiY / 96f) / 2) * 2; lock (this) { videoWriter.Open( TempVideoPathName, gridActWidth, gridActHeight, 5, VideoCodec.MPEG4, gridActWidth * gridActHeight * 10 ); waveIn = new WaveInEvent(); waveIn_runing = true; writer = new WaveFileWriter(TempAudioPathName, waveIn.WaveFormat); //开始录音,写数据 waveIn.DataAvailable += (s, a) => { if (RecordType == 1) { writer.Write(a.Buffer, 0, a.BytesRecorded); } }; //结束录音 waveIn.RecordingStopped += (s, a) => { writer.Dispose(); writer = null; waveIn.Dispose(); waveIn_runing = false; }; waveIn.StartRecording(); } }); SRTime = Convert.ToDateTime("2020-01-01 00:00:00"); Recorddt = DateTime.Now; ///启动截图 timer = new Timer(new TimerCallback(Timer_Elapsed), null, 0, 200); } /// /// 录制保存图片计时器 /// /// /// private void Timer_Elapsed(object sender) { if (RecordType == 1) { Dispatcher.Invoke(() => { SRTime = SRTime.AddMilliseconds(200); if (SRTime.Hour > 0) { TxbTime.Text = SRTime.ToString("HH:mm:ss"); } else { TxbTime.Text = SRTime.ToString("mm:ss"); } }); ThreadPool.QueueUserWorkItem(o => { RecordSaveImage(); }); } } #endregion 录制窗口 #region 分页 private void ImgXY() { imgCanvas.Width = APP.PageDrawList[APP.PageContextData.currpage - 1].ImageSizes.CenterX; imgCanvas.Height = APP.PageDrawList[APP.PageContextData.currpage - 1].ImageSizes.CenterY; imgCanvas.Margin = new Thickness(APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation.X, APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation.Y, 0, 0); } /// /// 跳转 /// private void JumpPageClick() { myblackboard.changepage(APP.PageContextData.currpage - 1); ScroMain.ScrollToVerticalOffset(0); if (BtnImport.IsEnabled) { ///截图可用 BtnScreenshot.IsEnabled = true; } if (APP.PageContextData.currpage <= APP.PageDrawList.Count) { if (APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation != null) { APP.PageDrawList[APP.PageContextData.currpage - 1].IsImageLocation = true; } if (!string.IsNullOrWhiteSpace(txbCurrpage.Text) && APP.PageContextData.currpage <= APP.PageDrawList.Count && APP.PageContextData.currpage > 0 && !string.IsNullOrWhiteSpace(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath)) { if (APP.PageDrawList[APP.PageContextData.currpage - 1].ImgDocumentation) { if ("ppt".Equals(APP.PageDrawList[APP.PageContextData.currpage - 1].Type)) { imgCanvas.Source = null; imgDocumentation.Source = null; imgPPT.Source = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath)); BtnScreenshot.IsEnabled = false; } else { imgPPT.Source = null; imgCanvas.Source = null; imgDocumentation.Source = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath)); BtnScreenshot.IsEnabled = false; } } else { imgPPT.Source = null; imgDocumentation.Source = null; imgCanvas.Source = new BitmapImage(new Uri(APP.PageDrawList[APP.PageContextData.currpage - 1].PageImagePath)); APP.PageDrawList[APP.PageContextData.currpage - 1].IsImageLocation = false; if (APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation != null && APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation.X > 0) { mouseDown = false; imageOperationUtil.setMouseDown(mouseDown); ImgXY(); } } } else { imgPPT.Source = null; imgCanvas.Source = null; imgDocumentation.Source = null; } } } /// 上一页 private void last_button_Click(object sender, RoutedEventArgs e) { if (APP.PageContextData.currpage > 1) { mouseDown = false; imageOperationUtil.setMouseDown(mouseDown); HideAngleBorder(); APP.PageContextData.currpage -= 1; JumpPageClick(); } } /// /// 下一页 /// /// /// /// /// private void next_btn_Click(object sender, RoutedEventArgs e) { if (APP.PageContextData.currpage < APP.PageContextData.pagenum) { mouseDown = false; imageOperationUtil.setMouseDown(mouseDown); HideAngleBorder(); APP.PageContextData.currpage += 1; JumpPageClick(); } } #endregion 分页 #region 图像缩放,移动 private bool mouseDown; private System.Windows.Point mouseXY; /// /// x y轴 /// /// /// /// /// private void Domousemove(ContentControl img, System.Windows.Input.MouseEventArgs e) { if (e.LeftButton != MouseButtonState.Pressed) { return; } if (APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation != null && APP.PageDrawList[APP.PageContextData.currpage - 1].IsImageLocation) { return; } TransformGroup group = IMG.FindResource("Imageview") as TransformGroup; TranslateTransform transform = group.Children[1] as TranslateTransform; System.Windows.Point position = e.GetPosition(img); transform.X -= mouseXY.X - position.X; transform.Y -= mouseXY.Y - position.Y; mouseXY = position; APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation = new TranslateTransform { X = transform.X, Y = transform.Y }; } private void DowheelZoom(TransformGroup group, System.Windows.Point point, double delta) { System.Windows.Point pointToContent = group.Inverse.Transform(point); ScaleTransform transform = group.Children[0] as ScaleTransform; if (transform.ScaleX + delta < 0.1) { return; } transform.ScaleX += delta; transform.ScaleY += delta; TranslateTransform transform1 = group.Children[1] as TranslateTransform; transform1.X = -1 * ((pointToContent.X * transform.ScaleX) - point.X); transform1.Y = -1 * ((pointToContent.Y * transform.ScaleY) - point.Y); APP.PageDrawList[APP.PageContextData.currpage - 1].ImageLocation = new TranslateTransform { X = transform1.X, Y = transform1.Y }; APP.PageDrawList[APP.PageContextData.currpage - 1].ImageSizes = new ScaleTransform { CenterX = imgCanvas.ActualWidth, CenterY = imgCanvas.ActualHeight }; APP.PageDrawList[APP.PageContextData.currpage - 1].IsImageLocation = false; } private void IMG1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { ContentControl img = sender as ContentControl; if (img == null) { return; } img.CaptureMouse(); mouseDown = true; imageOperationUtil.setMouseDown(mouseDown); mouseXY = e.GetPosition(img); //Console.WriteLine("mouseXY.X = " + mouseXY.X + "; mouseXY.Y = " + mouseXY.Y); } private void IMG1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { ContentControl img = sender as ContentControl; if (img == null) { return; } img.ReleaseMouseCapture(); mouseDown = false; imageOperationUtil.setMouseDown(mouseDown); } private void IMG1_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) { ContentControl img = sender as ContentControl; if (img == null) { return; } if (mouseDown) { Domousemove(img, e); } } private void IMG1_MouseWheel(object sender, MouseWheelEventArgs e) { ContentControl img = sender as ContentControl; if (img == null) { return; } System.Windows.Point point = e.GetPosition(img); System.Windows.Point PicLocate = e.GetPosition(imgCanvas); TransformGroup group = IMG.FindResource("Imageview") as TransformGroup; double delta = e.Delta * 0.001; DowheelZoom(group, point, delta); } #endregion 图像缩放,移动 #region 更改设备连接状态 /// /// 更新设备状态显示 /// public void UpdateDevStatus() { if (APP.BoardStatus && (APP.PenStatus || APP.TQLPenStatus)) { Dispatcher.Invoke(new Action(() => { txbNotConnected.Text = "笔/板已连接"; txbNotConnecteds.Text = "笔/板已连接"; })); } else if (APP.BoardStatus) { Dispatcher.Invoke(new Action(() => { txbNotConnected.Text = "手写板已连接"; txbNotConnecteds.Text = "手写板已连接"; })); } else if (APP.PenStatus) { Dispatcher.Invoke(new Action(() => { txbNotConnected.Text = "智能笔已连接"; txbNotConnecteds.Text = "智能笔已连接"; })); } else if (APP.TQLPenStatus) { Dispatcher.Invoke(new Action(() => { txbNotConnected.Text = "智能笔已连接"; txbNotConnecteds.Text = "智能笔已连接"; })); } else { Dispatcher.Invoke(new Action(() => { txbNotConnected.Text = "未连接"; txbNotConnecteds.Text = "未连接"; })); } } #endregion 更改设备连接状态 #region 腾千里手写笔 private static float TQLA4_HEIGHT = (float)3509 / (float)300 * (float)25.4 / (float)1.524; /// /// TQL点阵笔宽高 /// private static float TQLA4_WIDTH = (float)2480 / (float)300 * (float)25.4 / (float)1.524; /// /// 是否在书写 /// private bool isTQLPenDown = false; //(float)1075 / (float)150 * (float)25.4 / (float)1.524; //OID4 //(float)1512 / (float)150 * (float)25.4 / (float)1.524; /// /// TQL初始化 /// public void InitTQLPPen() { if (APP.TQLPenevents == null) { APP.TQLPenevents = new PenEvents(1); } else { APP.TQLPenevents.InToType = 1; } } /// /// 笔落下 /// public void TQLDown() { isTQLPenDown = true; if (APP.PageContextData.currpage > 0) { Dispatcher.Invoke(new Action(() => { myblackboard.changepages(0, 0, true, Color, PenSize, APP.PageContextData.currpage - 1, 0); })); } } /// /// 笔书写 /// /// /// /// /// /// /// public void TQLPenWrite(double cx, double cy, int force) { //判断是否是落笔后输出的坐标,在设置悬浮模式下,落笔前的悬浮坐标不绘制 if (!isTQLPenDown) { return; } double PropW = blackboard_canvas.ActualWidth / TQLA4_WIDTH; double PropH = blackboard_canvas.ActualHeight / TQLA4_HEIGHT; //点 double tempX = cx * PropW; double tempY = cy * PropH; if (APP.PageContextData.currpage > 0) { Dispatcher.Invoke(new Action(() => { //0~1023,亦即有 1024 阶供应用软件后续应用之用,如笔锋笔触,暂无用 float Pressure = (float)force / 1023f; myblackboard.changepages(tempX, tempY, false, Color, PenSize, APP.PageContextData.currpage - 1, Pressure); #region 设置滚动条位置 //点在显示页面上方 if (tempY < ScroMain.VerticalOffset) { //滚动条当前位置 double RollCurrentLocation = ScroMain.VerticalOffset; //向上滚动至以点为中心需要滚动的距离 double UpRoll = (RollCurrentLocation - tempY) + (ScroMain.ActualHeight / 2); //如果小于0则等于0 double RollLocation = RollCurrentLocation - UpRoll; if (RollLocation < 0) { RollLocation = 0; } ////滚动条实际偏移量 //double RollOffset = RollCurrentLocation - RollLocation; ScroMain.ScrollToVerticalOffset(RollLocation); } //点在显示页面下方 if (tempY > ScroMain.VerticalOffset + ScroMain.ActualHeight) { //滚动条当前位置 double RollCurrentLocation = ScroMain.VerticalOffset; //向下滚动至以点为中心需要滚动的距离 double DownRoll = (tempY - RollCurrentLocation) - (ScroMain.ActualHeight / 2); //如果小于0则等于0 double RollLocation = RollCurrentLocation + DownRoll; //滚动条最大滚动值 double ScrollbarMaxNum = GridM.ActualHeight - ScroMain.ActualHeight; if (RollLocation > ScrollbarMaxNum) { RollLocation = ScrollbarMaxNum; } ////滚动条实际偏移量 //double RollOffset = RollLocation-RollCurrentLocation; ScroMain.ScrollToVerticalOffset(RollLocation); } #endregion 设置滚动条位置 if (tempX > 0 && tempY > 0) { System.Windows.Point getP = ScroMain.PointToScreen(new System.Windows.Point(tempX, tempY - ScroMain.VerticalOffset)); SetCursorPos((int)getP.X, (int)getP.Y); } })); } } /// /// 笔抬起 /// public void TQLUp() { isTQLPenDown = false; //stroke.Clear(); if (APP.PageContextData.currpage > 0) { Dispatcher.Invoke(new Action(() => { myblackboard.changepages(0, 0, true, Color, PenSize, APP.PageContextData.currpage - 1, 0); })); } } #endregion 腾千里手写笔 #region 图片拉伸移动 /// /// 点击标题栏 隐藏截图的四个点和线 /// /// /// /// /// private void Grid_MouseDown(object sender, MouseButtonEventArgs e) { imageOperationUtil.Grid_MouseDown(); } /// /// 隐藏图片四个点和线 /// private void HideAngleBorder() { imageOperationUtil.HideAngleBorder(); } private void imgCanvas_MouseMove(object sender, MouseEventArgs e) { imageOperationUtil.imgCanvas_MouseMove(sender, e); } private void imgCanvas_MouseUp(object sender, MouseButtonEventArgs e) { imageOperationUtil.imgCanvas_MouseUp(); } private void PicEMap_MouseDown(object sender, MouseButtonEventArgs e) { imageOperationUtil.PicEMap_MouseDown(sender, e); } private void RectRightUp_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e) { imageOperationUtil.RectRightUp_DragCompleted(); } private void RectRightUp_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e) { imageOperationUtil.RectRightUp_DragDelta(sender, e); } private void RectRightUp_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e) { imageOperationUtil.RectRightUp_DragStarted(sender, e); } /// /// 鼠标左键点击事件 /// /// /// /// /// private void Window_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e) { imageOperationUtil.Window_MouseLeftButtonDown_1(); } #endregion 图片拉伸移动 #region 录屏 录制 截图 导入文档 增加 主页面显示 /// /// 录屏 录制 截图 导入文档 增加 主页面显示 /// private void Record() { PageHide(); GridMain.Visibility = Visibility.Visible; GridRecordingTitle.Visibility = Visibility.Visible; if (APP.PageContextData.pagenum > 0) { GridPage.Visibility = Visibility.Visible; } DataContext = APP.PageContextData; } #endregion 录屏 录制 截图 导入文档 增加 主页面显示 #region 页码跳转 /// /// 确定跳转 /// /// /// /// /// private void BtnJumpPage_Click(object sender, RoutedEventArgs e) { int JumpPage = 0; if (JumpPage < 1) { JumpPage = 1; } if (JumpPage > int.Parse(txbTotalpage.Text)) { JumpPage = int.Parse(txbTotalpage.Text); } #region 跳转 APP.PageContextData.currpage = JumpPage; JumpPageClick(); #endregion 跳转 } private void txtJump_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == Key.Enter) { BtnJumpPage_Click(null, null); } } /// /// 只允许输入数字 /// /// /// /// /// private void txtJump_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex re = new Regex("[^0-9.-]+"); e.Handled = re.IsMatch(e.Text); } #endregion 页码跳转 #region TQL打印 public static string gPrintFileName; private iTextSharp.text.Document document; private bool gbInitDone = false; /// /// 授权码 /// private string gKeyStr; private TmatrixClass TMC = new TmatrixClass(); /// /// 授权文件位置 /// private string TQLAuthorizationPath; /// /// 铺码 /// private bool GenerateCode(string PDFPath) { try { if (gbInitDone == false) { MessageWindow.Show("打印功能无法使用,无效授权。"); return false; } try { string directoryPath = FileToolsCommon.GetDirectoryName(PDFPath); FileToolsCommon.DeleteDirectory(directoryPath + "Bg with Images/"); FileToolsCommon.DeleteDirectory(directoryPath + "Bg with Vector Images/"); FileToolsCommon.DeleteDirectory(directoryPath + "Bg without Vector Images/"); FileToolsCommon.DeleteDirectory(directoryPath + "Vector Images/"); } catch (Exception) { } PDFPath = PDFPath.Replace("/", "\\"); //初始页 bool[] bPublishImageType = new bool[4]; bPublishImageType[0] = false; bPublishImageType[1] = false; bPublishImageType[2] = false; bPublishImageType[3] = true; int[] gPointType = { 0, 0, 0, 0, 1 }; int[] gPointDPI = { 0, 0, 0, 0, 1 }; string sGenerateResult = TMC.GenerateTmatrixCode_OID4( gKeyStr, PDFPath, 0, gPointType, bPublishImageType, gPointDPI ); if (sGenerateResult.Substring(0, 1) == "1") { Dispatcher.Invoke(() => { MessageWindow.Show("打印功能无法使用,无效授权。"); }); return false; } return true; } catch (Exception ex) { Dispatcher.Invoke(() => { MessageWindow.Show("打印失败:" + ex.Message); }); return false; } } /// /// TQL初始化打印 /// private void TQLPrintInit() { ///初始化 if (TMC.TmatrixInitialize() == false) { } else { gbInitDone = true; } document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0); try { TQLAuthorizationPath = FileToolsCommon.GetFileAbsolutePath("/LatticeXML/S0_O000_B0000_P000-255.tmx"); StreamReader gsr = new StreamReader(TQLAuthorizationPath); gKeyStr = gsr.ReadLine(); gsr.Close(); string KeyCheckResult = TMC.TmatrixKeyCheck_OID4(gKeyStr); if (KeyCheckResult.Substring(0, 1) == "1") { MessageWindow.Show("打印服务授权过期,请联系厂家更换授权!"); LogHelper.WriteErrLog("打印服务授权过期:" + KeyCheckResult, null); gbInitDone = false; } else if (KeyCheckResult.Substring(0, 1) == "0") { } } catch (Exception ex) { LogHelper.WriteErrLog("打印服务授权失败:" + ex.Message, ex); MessageWindow.Show("打印服务授权失败,请联系厂家!"); gbInitDone = false; } } #endregion TQL打印 #region 打印界面 /// /// 下拉框数据源 /// public DataTable printlist = new DataTable(); private DataTable dtComponentsUniqueNo; private double hei = 0; private int msgnum = 0; private int num = 0; /// /// 打印状态消息 /// private string PrintMsg = "打印中"; /// /// 打印进度 /// private System.Timers.Timer timesPrint; /// /// 打印消息 /// private System.Timers.Timer timesPrintMsg; private double wit = 0; /// /// 初始化页面 /// /// /// /// /// /// /// public void InitializePrint(string _imgPath, double _wit, double _hei) { wit = _wit; hei = _hei; if (!string.IsNullOrWhiteSpace(_imgPath)) { imgPri.Source = new BitmapImage(new Uri(_imgPath)); } else { imgPri.Source = null; } GridPrintMask.Visibility = Visibility.Collapsed; } /// /// 打印初始化 /// public async void InitPrint() { ResizeMode = ResizeMode.NoResize; await Task.Run(() => { List defaList = ZPrintUtils.GetLocalPrinters(); if (defaList.Count > 0) { printlist.Columns.Add("Value"); printlist.Columns.Add("Key"); for (int i = 0; i < defaList.Count; i++) { //创建一行 DataRow row = printlist.NewRow(); //将此行添加到table中 printlist.Rows.Add(row); printlist.Rows[i]["Value"] = defaList[i]; printlist.Rows[i]["Key"] = i.ToString(); } dtComponentsUniqueNo = printlist.DefaultView.ToTable(); } }); cmbClass.ItemsSource = dtComponentsUniqueNo.DefaultView; cmbClass.SelectedIndex = 0; TQLPrintInit(); } /// /// 生成图片 /// /// /// 图片地址 /// /// /// 保存位置 /// /// /// 图片位置 /// /// /// 错误消息 /// /// /// private bool MergerPrintImg(string _path, string _saveimg, RectangleF _rectangle, out string errmsg) { errmsg = null; try { Bitmap bitmap = null; //创建要显示的图片对象,根据参数的个数设置宽度 Bitmap backgroudImg = new Bitmap((int)/*GridM.ActualWidth*/wit, (int)/*GridM.ActualHeight*/hei); Graphics g = Graphics.FromImage(backgroudImg); //清除画布,背景设置为白色 g.Clear(System.Drawing.Color.White); if (!string.IsNullOrWhiteSpace(_path)) { bitmap = ImageHelper.ReadBitmapFile(_path); g.DrawImage(bitmap, _rectangle); } #region 添加箭头 string Str = "↑"; SolidBrush mybrush = new SolidBrush(System.Drawing.Color.Black); //设置默认画刷颜色 Font myfont = new System.Drawing.Font("黑体", 14); //设置默认字体格式 g.DrawString(Str, myfont, mybrush, new System.Drawing.Rectangle((int)wit - 50, 20, 50, 50)); #endregion 添加箭头 backgroudImg.Save(_saveimg); g.Dispose(); backgroudImg.Dispose(); if (bitmap != null) { bitmap.Dispose(); } GC.Collect(); return true; } catch (Exception ex) { errmsg = ex.Message; LogHelper.WriteErrLog("【截图合成】(MergerImg)图片合成失败:" + ex.Message, ex); return false; } } /// /// 开始打印 /// private void StartPrint(PrintModel printModel) { try { document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0f, 0f, 0f, 0f); PrintMsg = "生成文件"; msgnum = 0; string SourcePath1 = printModel.filepath; try { SourcePath1 = SourcePath1.Replace("/", "\\"); FileStream fs = new FileStream(SourcePath1, FileMode.Create, FileAccess.ReadWrite); document.AddAuthor("星火微课");//作者 document.AddCreationDate();//创建时候 document.AddCreator("星火微课");//创建者 document.AddSubject("点阵文件");//主题 document.AddTitle("PrintTmatrixCode");//标题 document.AddKeywords("Print"); document.AddHeader("TmatrixCode", "0"); iTextSharp.text.pdf.PdfWriter.GetInstance(document, fs); } catch (Exception) { } document.Open(); iTextSharp.text.Image image; for (int i = 0; i < APP.PageDrawList.Count; i++) { long ii = Timestamp(); string directoryPath = AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; string filePathOutPut = Path.Combine(directoryPath, string.Format("print{0}{1}.jpg", ii, i)); RectangleF rectangleFs = new RectangleF(); MergerPrintImg("", filePathOutPut, rectangleFs, out string errmsg); image = iTextSharp.text.Image.GetInstance(filePathOutPut); if (string.IsNullOrEmpty(APP.PageDrawList[i].PageImagePath))//没有图片 { } else if (APP.PageDrawList[i].ImgDocumentation == true && !APP.PageDrawList[i].Type.Equals("ppt")) { image = iTextSharp.text.Image.GetInstance(APP.PageDrawList[i].PageImagePath); } else { RectangleF rectangleF = new RectangleF(0, 0, 0, 0); Dispatcher.Invoke(() => { rectangleF = new RectangleF { Width = (float)APP.PageDrawList[i].ImageSizes.CenterX, Height = (float)APP.PageDrawList[i].ImageSizes.CenterY, X = (float)APP.PageDrawList[i].ImageLocation.X, Y = (float)APP.PageDrawList[i].ImageLocation.Y }; }); string msgs = string.Empty; bool isImg = MergerPrintImg(APP.PageDrawList[i].PageImagePath, filePathOutPut, rectangleF, out msgs); if (isImg) { image = iTextSharp.text.Image.GetInstance(filePathOutPut); } else { image = iTextSharp.text.Image.GetInstance(APP.PageDrawList[i].PageImagePath); } } if (image.Height > iTextSharp.text.PageSize.A4.Height) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height); } else if (image.Width > iTextSharp.text.PageSize.A4.Width) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height); } image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.NewPage(); document.Add(image); } document.Close(); } catch (Exception ex) { Dispatcher.Invoke(() => { BtnPrint.IsEnabled = true; timesPrint.Stop(); timesPrintMsg.Stop(); GridPrintMask.Visibility = Visibility.Collapsed; MessageWindow.Show(ex.Message); return; }); LogHelper.WriteErrLog("打印转换PDF失败,原因:" + ex.Message, ex); } //PDF位置 string SourcePath = printModel.filepath; int PrinterNum = printModel.num; string PrinterName = printModel.printname; if (isHasCode) { PrintMsg = "铺码中"; msgnum = 0; Thread.Sleep(500); //腾千里生成点阵文件 if (GenerateCode(SourcePath)) { //打印机名称 string directoryPath = FileToolsCommon.GetDirectoryName(SourcePath) + "Bg with Images/"; string[] strs = FileToolsCommon.GetFileNames(directoryPath); try { // 腾千里会根据原PDF的页数生成多个PDF文件 for (int i = 0; i < strs.Count(); i++) { timesPrint.Stop(); PrintMsg = "正在打印第" + (i + 1) + "/" + strs.Count() + "页中"; msgnum = 0; num = 0; timesPrint.Interval = 100; timesPrint.Start(); string fileName = strs[i]; //打印文件 ZPrintUtils.Print(fileName, PrinterName); } Dispatcher.Invoke(() => { BtnPrint.IsEnabled = true; num = 99; timesPrint.Stop(); pgbProcess.Value = 100; lbProcess.Content = "100%"; GridPrintMask.Visibility = Visibility.Collapsed; //MessageWindow.Show("已加入打印机队列,打印中。"); }); } catch (Exception ex) { Dispatcher.Invoke(() => { MessageWindow.Show("打印失败:" + ex.Message); BtnPrint.IsEnabled = true; timesPrint.Stop(); GridPrintMask.Visibility = Visibility.Collapsed; return; }); } } else { Dispatcher.Invoke(() => { BtnPrint.IsEnabled = true; timesPrint.Stop(); timesPrintMsg.Stop(); GridPrintMask.Visibility = Visibility.Collapsed; return; }); } } else { //打印文件 ZPrintUtils.Print(SourcePath, PrinterName); Dispatcher.Invoke(() => { BtnPrint.IsEnabled = true; num = 99; timesPrint.Stop(); pgbProcess.Value = 100; lbProcess.Content = "100%"; GridPrintMask.Visibility = Visibility.Collapsed; //MessageWindow.Show("已加入打印机队列,打印中。"); }); } } /// /// 计时器 /// /// /// /// /// private void Times_ElapsedClick(object sender, System.Timers.ElapsedEventArgs e) { Dispatcher.Invoke(() => { pgbProcess.Value = num; lbProcess.Content = num.ToString() + "%"; if (num < 99) { num++; timesPrint.Interval += (num / 2); } else { timesPrint.Stop(); } }); } /// /// 消息 /// /// /// /// /// private void TimesPrintMsg_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (msgnum > 5) msgnum = 0; else msgnum++; string point = ""; point = point.ToString().PadRight(msgnum, '.'); Dispatcher.Invoke(() => { LabPrintMessage.Content = PrintMsg + point; }); } #endregion 打印界面 #region 笔事件回调 public void penPointEvent(byte bIndex, byte bPenStatus, short bx, short by, short bPress, int m_nDeviceW, int m_nDeviceH) { //17是按下,16是抬起 if (bPenStatus == 16 || bPenStatus == 0) { //stroke.Clear(); if (APP.PageContextData.currpage > 0) { Dispatcher.Invoke(new Action(() => { myblackboard.changepages(0, 0, true, Color, PenSize, APP.PageContextData.currpage - 1, 0); })); } } double PropW = blackboard_canvas.ActualWidth / m_nDeviceH; double PropH = blackboard_canvas.ActualHeight / m_nDeviceW; //点 double tempY = (m_nDeviceW - bx) * PropH; double tempX = by * PropW; //pageSerial //点阵IP地址 与打印的页面关联 if (APP.PageContextData.currpage > 0) { Dispatcher.Invoke(new Action(() => { float Pressure = bPress / 100f; if (bPress > 0) { myblackboard.changepages(tempX, tempY, false, Color, PenSize, APP.PageContextData.currpage - 1, Pressure); } #region 设置滚动条位置 //点在显示页面上方 if (tempY < ScroMain.VerticalOffset) { //滚动条当前位置 double RollCurrentLocation = ScroMain.VerticalOffset; //向上滚动至以点为中心需要滚动的距离 double UpRoll = (RollCurrentLocation - tempY) + (ScroMain.ActualHeight / 2); //如果小于0则等于0 double RollLocation = RollCurrentLocation - UpRoll; if (RollLocation < 0) { RollLocation = 0; } ////滚动条实际偏移量 //double RollOffset = RollCurrentLocation - RollLocation; ScroMain.ScrollToVerticalOffset(RollLocation); } //点在显示页面下方 if (tempY > ScroMain.VerticalOffset + ScroMain.ActualHeight) { //滚动条当前位置 double RollCurrentLocation = ScroMain.VerticalOffset; //向下滚动至以点为中心需要滚动的距离 double DownRoll = (tempY - RollCurrentLocation) - (ScroMain.ActualHeight / 2); //如果小于0则等于0 double RollLocation = RollCurrentLocation + DownRoll; //滚动条最大滚动值 double ScrollbarMaxNum = GridM.ActualHeight - ScroMain.ActualHeight; if (RollLocation > ScrollbarMaxNum) { RollLocation = ScrollbarMaxNum; } ////滚动条实际偏移量 //double RollOffset = RollLocation-RollCurrentLocation; ScroMain.ScrollToVerticalOffset(RollLocation); } #endregion 设置滚动条位置 if (tempX > 0 && tempY > 0) { //System.Windows.Point getP = blackboard_canvas.PointToScreen(new System.Windows.Point(testX, testY)); System.Windows.Point getP = ScroMain.PointToScreen(new System.Windows.Point(tempX, tempY - ScroMain.VerticalOffset)); SetCursorPos((int)getP.X, (int)getP.Y); } })); } } public void penStatusEvent() { UpdateDevStatus(); } #endregion 笔事件回调 private void Window_Closed(object sender, EventArgs e) { Environment.Exit(0); } } public class PageData { public int PageCode { get; set; } public string PageName { get; set; } } }