diff --git a/ChineseSubtitleConversionTool/ChineseSubtitleConversionTool.csproj b/ChineseSubtitleConversionTool/ChineseSubtitleConversionTool.csproj index 0b2396f..bca356d 100644 --- a/ChineseSubtitleConversionTool/ChineseSubtitleConversionTool.csproj +++ b/ChineseSubtitleConversionTool/ChineseSubtitleConversionTool.csproj @@ -66,8 +66,11 @@ + + FormMain.cs + Designer ResXFileCodeGenerator diff --git a/ChineseSubtitleConversionTool/FormMain.Designer.cs b/ChineseSubtitleConversionTool/FormMain.Designer.cs index 909a81c..bf97005 100644 --- a/ChineseSubtitleConversionTool/FormMain.Designer.cs +++ b/ChineseSubtitleConversionTool/FormMain.Designer.cs @@ -28,7 +28,6 @@ protected override void Dispose(bool disposing) /// private void InitializeComponent() { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain)); this.txtShow = new System.Windows.Forms.TextBox(); this.btnToSimplified = new System.Windows.Forms.Button(); this.btnToTraditional = new System.Windows.Forms.Button(); @@ -58,6 +57,7 @@ private void InitializeComponent() this.rbConvertQuick = new System.Windows.Forms.RadioButton(); this.label6 = new System.Windows.Forms.Label(); this.groupConvertOption = new System.Windows.Forms.GroupBox(); + this.btnSaveProfile = new System.Windows.Forms.Button(); this.tabControlMain.SuspendLayout(); this.tabPageCommon.SuspendLayout(); this.tabPageBatch.SuspendLayout(); @@ -76,7 +76,6 @@ private void InitializeComponent() this.txtShow.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtShow.Size = new System.Drawing.Size(555, 246); this.txtShow.TabIndex = 0; - this.txtShow.Text = resources.GetString("txtShow.Text"); // // btnToSimplified // @@ -164,7 +163,7 @@ private void InitializeComponent() this.txtFileName.Name = "txtFileName"; this.txtFileName.Size = new System.Drawing.Size(174, 21); this.txtFileName.TabIndex = 1; - this.txtFileName.Text = "{name}.cs{exten}"; + this.txtFileName.Text = "{name}.sc{exten}"; this.txtFileName.TextChanged += new System.EventHandler(this.txtFileName_TextChanged); // // txtPath @@ -362,6 +361,7 @@ private void InitializeComponent() this.rbConvertHigh.Text = "高精度"; this.rbConvertHigh.UseVisualStyleBackColor = true; this.rbConvertHigh.CheckedChanged += new System.EventHandler(this.rbConvertOption_CheckedChanged); + this.rbConvertHigh.CheckedChanged += new System.EventHandler(this.rbConvertHigh_CheckedChanged); // // rbConvertOldWord // @@ -400,6 +400,7 @@ private void InitializeComponent() // this.groupConvertOption.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); + this.groupConvertOption.Controls.Add(this.btnSaveProfile); this.groupConvertOption.Controls.Add(this.rbConvertHigh); this.groupConvertOption.Controls.Add(this.rbConvertOldWord); this.groupConvertOption.Controls.Add(this.rbConvertQuick); @@ -410,6 +411,17 @@ private void InitializeComponent() this.groupConvertOption.TabIndex = 5; this.groupConvertOption.TabStop = false; // + // btnSaveProfile + // + this.btnSaveProfile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.btnSaveProfile.Location = new System.Drawing.Point(490, 12); + this.btnSaveProfile.Name = "btnSaveProfile"; + this.btnSaveProfile.Size = new System.Drawing.Size(75, 23); + this.btnSaveProfile.TabIndex = 5; + this.btnSaveProfile.Text = "保存配置"; + this.btnSaveProfile.UseVisualStyleBackColor = true; + this.btnSaveProfile.Click += new System.EventHandler(this.btnSaveProfile_Click); + // // FormMain // this.AllowDrop = true; @@ -468,6 +480,7 @@ private void InitializeComponent() private System.Windows.Forms.GroupBox groupConvertOption; private System.Windows.Forms.Button btnCopy; private System.Windows.Forms.ProgressBar progressBarPercentage; + private System.Windows.Forms.Button btnSaveProfile; } } diff --git a/ChineseSubtitleConversionTool/FormMain.cs b/ChineseSubtitleConversionTool/FormMain.cs index 3b11790..7215a7a 100644 --- a/ChineseSubtitleConversionTool/FormMain.cs +++ b/ChineseSubtitleConversionTool/FormMain.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; @@ -23,7 +22,6 @@ public partial class FormMain : Form #region 初始化相关 public FormMain() { - Global.Init(); InitializeComponent(); Config = MainConfig.Load(); } @@ -47,55 +45,42 @@ private void FormMain_Load(object sender, EventArgs e) txtFileName.Text = Config.FileName; rbConvertHigh.Enabled = false; - rbConvertOldWord.Enabled = false; - rbConvertQuick.Enabled = false; - Task.Factory.StartNew(() => + rbConvertOldWord.Enabled = true; + rbConvertQuick.Enabled = true; + if (Type.GetTypeFromProgID("Word.Application") != null) { - try + if (Config.ConvertOption == enumConvertOption.Null) { - OfficeWordConvert owc = new OfficeWordConvert(); - owc.Dispose(); - if (Config.ConvertOption == enumConvertOption.Null) - { - Config.ConvertOption = enumConvertOption.High; - } - this.Invoke(new Action(() => - { - rbConvertHigh.Enabled = true; - })); + Config.ConvertOption = enumConvertOption.High; } - catch (Exception err) + rbConvertHigh.Enabled = true; + } + else + { + switch (Config.ConvertOption) { - if (Config.ConvertOption == enumConvertOption.Null) - { - Config.ConvertOption = enumConvertOption.OldWord; - } - this.Invoke(new Action(() => - { - rbConvertHigh.Enabled = false; - Console.WriteLine(err.Message); - })); + case enumConvertOption.Null: + Config.ConvertOption = enumConvertOption.Quick; + break; + case enumConvertOption.High: + Config.ConvertOption = enumConvertOption.Quick; + break; } - this.Invoke(new Action(() => - { - rbConvertOldWord.Enabled = true; - rbConvertQuick.Enabled = true; - switch (Config.ConvertOption) - { - case enumConvertOption.High: - rbConvertHigh.Checked = true; - break; - case enumConvertOption.OldWord: - rbConvertOldWord.Checked = true; - break; - case enumConvertOption.Quick: - case enumConvertOption.Null: - default: - rbConvertQuick.Checked = true; - break; - } - })); - }); + rbConvertHigh.Enabled = false; + } + + switch (Config.ConvertOption) + { + case enumConvertOption.High: + rbConvertHigh.Checked = true; + break; + case enumConvertOption.Quick: + rbConvertQuick.Checked = true; + break; + case enumConvertOption.OldWord: + rbConvertOldWord.Checked = true; + break; + } TipObject = new ToolTip(); TipObject.AutoPopDelay = 10000; //工具提示保持可见的时间期限 @@ -105,31 +90,24 @@ private void FormMain_Load(object sender, EventArgs e) TipObject.UseAnimation = true; //动画效果 TipObject.UseFading = true; //淡入淡出效果 TipObject.IsBalloon = true; //气球状外观 - TipObject.SetToolTip(this.txtFileName, "替换符说明:{name}原文件名称,{exten}文件扩展名,{num}文件序号"); + TipObject.SetToolTip(this.txtFileName, "替换符说明:{name}原文件名称,{exten}文件扩展名,{num}文件序号,{name}删除原文件名中最后出现的xxx"); TipObject.SetToolTip(this.rbConvertQuick, "选择后可较快的转换完成,全局有效!"); TipObject.SetToolTip(this.rbConvertOldWord, "选择后可有效避免出现??异常文字,全局有效!"); TipObject.SetToolTip(this.rbConvertHigh, "选择后会结合上下文语义转换速度慢,全局有效!"); } /// - /// 关闭窗体保存配置 + /// 关闭窗体 /// /// /// private void FormMain_FormClosing(object sender, FormClosingEventArgs e) { this.Hide(); - try + WordApplicationPool.CreatingWordApplication = false; + lock (WordApplication.CreatingWordApplicationLock)//初始化结束后再退出,否则新打开的word会残留在后台 { - Config.ControlTabIndex = tabControlMain.SelectedIndex; - Config.FormatIndex = cbFormat.SelectedIndex; - Config.EncodeIndex = cbEncode.SelectedIndex; - Config.FileName = txtFileName.Text; - MainConfig.Save(Config); - } - catch (Exception err) - { - Console.WriteLine(err.Message); + } } @@ -183,7 +161,7 @@ private void FormMain_DragEnter(object sender, DragEventArgs e) private void FormMain_DragDrop(object sender, DragEventArgs e) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop, true); - if (paths.Length > 1) + if (paths.Length > 1 || tabControlMain.SelectedIndex == 1) { tabControlMain.SelectedIndex = 1; txtPath.Text = Path.GetDirectoryName(paths[0].Trim()); @@ -399,16 +377,16 @@ private void listViewFile_ColumnClick(object sender, ColumnClickEventArgs e) private void cbFormat_SelectionChangeCommitted(object sender, EventArgs e) { string strFileStyle = txtFileName.Text.Trim(); - if (strFileStyle == "{name}.cs{exten}" || strFileStyle == "{name}.ct{exten}") + if (strFileStyle == "{name}<.tc>.sc{exten}" || strFileStyle == "{name}<.sc>.tc{exten}") { ComboBox comboBox = (ComboBox)sender; if (comboBox.SelectedIndex == 0) { - strFileStyle = "{name}.cs{exten}"; + strFileStyle = "{name}<.tc>.sc{exten}"; } else if (comboBox.SelectedIndex == 1) { - strFileStyle = "{name}.ct{exten}"; + strFileStyle = "{name}<.sc>.tc{exten}"; } txtFileName.Text = strFileStyle; } @@ -470,6 +448,10 @@ private void btnStartConvert_Click(object sender, EventArgs e) } pbConvert.Value = 0; pbConvert.Maximum = dicFile.Count; + if(convertOption == enumConvertOption.High) + { + WordApplicationPool.InitSemaphore(dicFile.Count); + } btnStartConvert.Hide(); int cnt = 0; Stopwatch Watch = new Stopwatch(); @@ -495,6 +477,7 @@ private void btnStartConvert_Click(object sender, EventArgs e) if (cnt >= fileLength) { Watch.Stop(); + WordApplicationPool.CreatingWordApplication = false; MessageBox.Show("转换完成,共输出" + pbConvert.Value + "个字幕文件,耗时" + string.Format("{0:0.###}", Watch.Elapsed.TotalSeconds) + "秒。", "转换完成", MessageBoxButtons.OK, MessageBoxIcon.Information); pbConvert.Value = 0; btnStartConvert.Show(); @@ -522,6 +505,30 @@ private void rbConvertOption_CheckedChanged(object sender, EventArgs e) } } + private void rbConvertHigh_CheckedChanged(object sender, EventArgs e) + { + RadioButton radioButton = (RadioButton)sender; + if (radioButton.Checked) + { + Task.Factory.StartNew(() => + { + try + { + WordApplicationPool.InitPool(); + } + catch (Exception err) + { + this.Invoke(new Action(() => + { + rbConvertHigh.Enabled = false; + rbConvertQuick.Checked = true; + })); + Console.WriteLine(err); + } + }); + } + } + #endregion #region 列表相关 @@ -584,6 +591,17 @@ private void LoadDirectoryFile(string path, ListView listView) /// private void UpdataListViewFileName(ListView listView, string nameStyle) { + String exclude = null; + int startIndex = nameStyle.IndexOf("{name}<"); + if (startIndex != -1) + { + int endIndex = nameStyle.IndexOf(">", startIndex + 7); + if (endIndex != -1) + { + exclude = nameStyle.Substring(startIndex + 7, endIndex - startIndex - 7); + nameStyle = nameStyle.Substring(0, startIndex + 6) + nameStyle.Substring(endIndex + 1); + } + } if (CheckFileStyle(nameStyle, out string msg)) { listView.BeginUpdate(); @@ -592,7 +610,7 @@ private void UpdataListViewFileName(ListView listView, string nameStyle) string filePath = item.SubItems[2].Text; if (File.Exists(filePath)) { - item.SubItems[1].Text = Path.GetFileName(MakeFileName(filePath, nameStyle, Convert.ToInt32(item.Text).ToString().PadLeft(listView.Items.Count.ToString().Length, '0'))); + item.SubItems[1].Text = Path.GetFileName(MakeFileName(filePath, nameStyle, exclude, Convert.ToInt32(item.Text).ToString().PadLeft(listView.Items.Count.ToString().Length, '0'))); } } listView.EndUpdate(); @@ -653,7 +671,6 @@ public string StringToSimlified(string str, enumConvertOption convertOption = en isWait = false; HighConvert.BindConvertEvent(ChangeProcessBarValue); string ret = HighConvert.Cht2Chs(str); - HighConvert.Dispose(); return ret; default: return ""; @@ -695,7 +712,6 @@ public string StringToTraditional(string str, enumConvertOption convertOption = isWait = false; HighConvert.BindConvertEvent(ChangeProcessBarValue); string ret = HighConvert.Chs2Cht(str); - HighConvert.Dispose(); return ret; default: return ""; @@ -759,10 +775,19 @@ private void ChangeProcessBarValue(object sender, double percentage) /// 返回是否合法 public bool CheckFileStyle(string fileStyle, out string msg) { + int startIndex = fileStyle.IndexOf("{name}<"); + if (startIndex != -1) + { + int endIndex = fileStyle.IndexOf(">", startIndex+7); + if (endIndex != -1) + { + fileStyle = fileStyle.Substring(0, startIndex+6) + fileStyle.Substring(endIndex + 1); + } + } msg = ""; if (fileStyle.IndexOf("{name}") == -1 && fileStyle.IndexOf("{num}") == -1) { - msg = "文件名中必须包含{name},请检查后修改再试。"; + msg = "文件名中必须包含{name}或{num},请检查后修改再试。"; return false; } if (fileStyle.IndexOf("{exten}") == -1) @@ -784,11 +809,19 @@ public bool CheckFileStyle(string fileStyle, out string msg) /// 源名称 /// 目标名称样式 /// - public string MakeFileName(string sourceName, string styleName, string num = "") + public string MakeFileName(string sourceName, string styleName,String exclude, string num = "") { string path = Path.GetDirectoryName(sourceName) + "\\"; string fileName = Path.GetFileNameWithoutExtension(sourceName); string fileExt = Path.GetExtension(sourceName); + if (exclude != null) + { + int lastIndex = fileName.LastIndexOf(exclude); + if (lastIndex != -1) + { + fileName = fileName.Substring(0, lastIndex) + fileName.Substring(lastIndex + exclude.Length); ; + } + } return path + styleName.Replace("{name}", fileName).Replace("{exten}", fileExt).Replace("{num}", num); } @@ -908,9 +941,25 @@ public bool SaveFile(string path, string text, string encode = "UTF-8") } } - #endregion + #endregion + private void btnSaveProfile_Click(object sender, EventArgs e) + { + Global.Init(); + try + { + Config.ControlTabIndex = tabControlMain.SelectedIndex; + Config.FormatIndex = cbFormat.SelectedIndex; + Config.EncodeIndex = cbEncode.SelectedIndex; + Config.FileName = txtFileName.Text; + MainConfig.Save(Config); + } + catch (Exception err) + { + MessageBox.Show(err.Message, "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } /// diff --git a/ChineseSubtitleConversionTool/FormMain.resx b/ChineseSubtitleConversionTool/FormMain.resx index 3ed6152..1af7de1 100644 --- a/ChineseSubtitleConversionTool/FormMain.resx +++ b/ChineseSubtitleConversionTool/FormMain.resx @@ -117,51 +117,4 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 普通转换 -可以直接将字幕文件拖拽到软件中,自动读取字幕文件内容,点击“转为简体”或“转为繁体”完成转换,点击“保存”按钮可以输出保存。 - -批量转换 -可以直接将含有字幕的文件夹拖拽到软件中,选择转换的格式,填写输出的文件名样式,点击“开始转换”即可完成转换。 - -批量转换使用多线程技术,转换过程UI不卡顿,其他功能可正常同步使用,方便并快捷。 - -需要注意当目标“文件名”与源文件或已存在文件同名时会覆盖掉已有文件,请注意备份源字幕文件。 - -批量转换将自动获取该目录下的全部字幕文件(包括ASS、SSA、SRT、LRC、TXT),其他格式文件不会读取。 - -文件名样式说明 -批量转换使用的是文件名样式替换掉替换符,替换符使用{}包裹,已有替换符如下: - -{name} 源文件名称(不包含路径与扩展名) - -{exten} 源文件扩展名,必须存在的替换符 - -{num} 文件序号,将列表中的序号使用在文件名中 - -文件名样式中除替换符以外的字符将原样输出,需要注意所有字符必须符合文件名规范,且不能存在重复的文件名,否则将出现保存异常。 - -如果要使用源文件名替换掉旧的字幕文件可输入:{name}{exten} - -如果文件名样式格式存在问题,文件名样式文本框背景为红色,且不可进行转换。 - -转换选项 -此配置全局有效,针对普通转换与批量转换输出结果;启用不同转换选项输出的效果略有不同,可根据需要进行选择。 - -快速转换 -采用常用模板算法,快速输出转换结果,无语义转换功能,适合大量简单的语句转换。 - -优化古文字转换 -在快速转换的基础上优化古文字显示,主要应用场景是在含有古文字字符的文本中,转换速度仅次于快速转换。 - -默认勾选该选项,该模式下与快速转换效率相差无几,有效避免快速转换结果出现??的BUG。 - -当不勾选该选项时,文本中包含的古文字有可能会被转换成??。 - -高精度转换 -采用Office组件实现的繁简转换功能,可根据语义输出转换结果,转换速度较慢,适合需要明确语义的使用场景。 - -使用此选项必须已安装Office组件,否则此选项不可用。 - - \ No newline at end of file diff --git a/ChineseSubtitleConversionTool/Global.cs b/ChineseSubtitleConversionTool/Global.cs index 1374cfe..13b01c7 100644 --- a/ChineseSubtitleConversionTool/Global.cs +++ b/ChineseSubtitleConversionTool/Global.cs @@ -1,9 +1,6 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Reflection; -using System.Text; using System.Windows.Forms; namespace ChineseSubtitleConversionTool diff --git a/ChineseSubtitleConversionTool/ListViewSort.cs b/ChineseSubtitleConversionTool/ListViewSort.cs index e4a9c7d..176ac8a 100644 --- a/ChineseSubtitleConversionTool/ListViewSort.cs +++ b/ChineseSubtitleConversionTool/ListViewSort.cs @@ -1,8 +1,5 @@ using System; using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Windows.Forms; namespace ChineseSubtitleConversionTool diff --git a/ChineseSubtitleConversionTool/MainConfig.cs b/ChineseSubtitleConversionTool/MainConfig.cs index 86f3bc9..1e879fe 100644 --- a/ChineseSubtitleConversionTool/MainConfig.cs +++ b/ChineseSubtitleConversionTool/MainConfig.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; namespace ChineseSubtitleConversionTool { @@ -14,7 +10,7 @@ public class MainConfig public int ControlTabIndex { get; set; } = 0; public int FormatIndex { get; set; } = 0; public int EncodeIndex { get; set; } = 0; - public string FileName { get; set; } = "{name}.cs{exten}"; + public string FileName { get; set; } = "{name}<.tc>.sc{exten}"; public MainConfig() { diff --git a/ChineseSubtitleConversionTool/OfficeWordConvert.cs b/ChineseSubtitleConversionTool/OfficeWordConvert.cs index 11c0266..502d934 100644 --- a/ChineseSubtitleConversionTool/OfficeWordConvert.cs +++ b/ChineseSubtitleConversionTool/OfficeWordConvert.cs @@ -1,17 +1,8 @@ -using Microsoft.Office.Interop.Word; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; - + namespace ChineseSubtitleConversionTool { public class OfficeWordConvert { - private _Application appWord; - private Document doc; /// /// 转换进度 @@ -32,26 +23,6 @@ private void EventConvertCallback(double p) } } - /// - /// 构造函数 - /// - public OfficeWordConvert() - { - appWord = new Application(); - object template = Missing.Value; - object newTemplate = Missing.Value; - object docType = Missing.Value; - object visible = true; - doc = appWord.Documents.Add(ref template, ref newTemplate, ref docType, ref visible); - } - - /// - /// 析构函数 - /// - ~OfficeWordConvert() - { - Dispose(); - } /// /// 简体转繁体函数 @@ -60,26 +31,11 @@ public OfficeWordConvert() /// 繁体字符串 public string Chs2Cht(string src) { - int len = src.Length; - int cnt = 0; - double p = 0; - StringBuilder sb = new StringBuilder(); - using (StringReader sr = new StringReader(src)) - { - string line; - while ((line = sr.ReadLine()) != null) - { - cnt += line.Length; - sb.AppendLine(chs_to_cht(line).TrimEnd()); - if (100 * cnt / len - p > 1) - { - p = 100 * cnt / len; - EventConvertCallback(p > 100 ? 100 : p); - } - } - } + WordApplication wordApplication = WordApplicationPool.Get(); + string str = wordApplication.chs_to_cht(src); + WordApplicationPool.Return(wordApplication); EventConvertCallback(100); - return sb.ToString(); + return str.Replace("\r", "\r\n"); } /// @@ -89,78 +45,13 @@ public string Chs2Cht(string src) /// 简体字符串 public string Cht2Chs(string src) { - int len = src.Length; - int cnt = 0; - double p = 0; - StringBuilder sb = new StringBuilder(); - using (StringReader sr = new StringReader(src)) - { - string line; - while ((line = sr.ReadLine()) != null) - { - cnt += line.Length; - sb.AppendLine(cht_to_chs(line).TrimEnd()); - if (100 * cnt / len - p > 1) - { - p = 100 * cnt / len; - EventConvertCallback(p > 100 ? 100 : p); - } - } - } + WordApplication wordApplication = WordApplicationPool.Get(); + string str = wordApplication.cht_to_chs(src); + WordApplicationPool.Return(wordApplication); EventConvertCallback(100); - return sb.ToString(); - } - - public void Dispose() - { - object saveChange = 0; - object originalFormat = Missing.Value; - object routeDocument = Missing.Value; - if (appWord != null) - { - appWord.Quit(ref saveChange, ref originalFormat, ref routeDocument); - } - doc = null; - appWord = null; - GC.Collect(); - GC.SuppressFinalize(this); + return str.Replace("\r","\r\n"); } - /// - /// 简体转繁体函数 - /// - /// 简体字符串 - /// 繁体字符串 - private string chs_to_cht(string src) - { - if (isStringChinese(src) == false) - { - return src; - } - appWord.Selection.Delete(); - appWord.Selection.TypeText(src); - appWord.Selection.Range.TCSCConverter(WdTCSCConverterDirection.wdTCSCConverterDirectionSCTC, true, true); - appWord.ActiveDocument.Select(); - return appWord.Selection.Text; - } - - /// - /// 繁体转简体函数 - /// - /// 繁体字符串 - /// 简体字符串 - private string cht_to_chs(string src) - { - if (isStringChinese(src) == false) - { - return src; - } - appWord.Selection.Delete(); - appWord.Selection.TypeText(src); - appWord.Selection.Range.TCSCConverter(WdTCSCConverterDirection.wdTCSCConverterDirectionTCSC, true, true); - appWord.ActiveDocument.Select(); - return appWord.Selection.Text; - } /// /// 检查字符串中是否包含汉字 diff --git a/ChineseSubtitleConversionTool/Program.cs b/ChineseSubtitleConversionTool/Program.cs index 2e3a573..e896947 100644 --- a/ChineseSubtitleConversionTool/Program.cs +++ b/ChineseSubtitleConversionTool/Program.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Windows.Forms; namespace ChineseSubtitleConversionTool diff --git a/ChineseSubtitleConversionTool/Serialize.cs b/ChineseSubtitleConversionTool/Serialize.cs index 10f2d24..33ee9ba 100644 --- a/ChineseSubtitleConversionTool/Serialize.cs +++ b/ChineseSubtitleConversionTool/Serialize.cs @@ -1,9 +1,7 @@ using System; -using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; -using System.Text; using System.Xml.Serialization; namespace ChineseSubtitleConversionTool diff --git a/ChineseSubtitleConversionTool/WordApplication.cs b/ChineseSubtitleConversionTool/WordApplication.cs new file mode 100644 index 0000000..cdafd35 --- /dev/null +++ b/ChineseSubtitleConversionTool/WordApplication.cs @@ -0,0 +1,78 @@ +using Microsoft.Office.Interop.Word; +using System; +using System.Reflection; + +namespace ChineseSubtitleConversionTool +{ + public class WordApplication + { + private _Application appWord; + private Document doc; + public static Object CreatingWordApplicationLock = new Object(); + public WordApplication() + { + lock (CreatingWordApplicationLock) + { + appWord = new Application(); + object template = Missing.Value; + object newTemplate = Missing.Value; + object docType = Missing.Value; + object visible = true; + doc = appWord.Documents.Add(ref template, ref newTemplate, ref docType, ref visible); + } + } + + /// + /// 析构函数 + /// + ~WordApplication() + { + Dispose(); + } + public void Dispose() + { + appWord.Selection.Delete(); + object saveChange = 0; + object originalFormat = Missing.Value; + object routeDocument = Missing.Value; + if (appWord != null) + { + appWord.Quit(ref saveChange, ref originalFormat, ref routeDocument); + } + doc = null; + appWord = null; + GC.Collect(); + GC.SuppressFinalize(this); + } + /// + /// 简体转繁体函数 + /// + /// 简体字符串 + /// 繁体字符串 + public string chs_to_cht(string src) + { + appWord.Selection.Delete(); + appWord.Selection.TypeText(src); + appWord.Selection.Range.TCSCConverter(WdTCSCConverterDirection.wdTCSCConverterDirectionSCTC, true, true); + appWord.ActiveDocument.Select(); + return appWord.Selection.Text; + } + + /// + /// 繁体转简体函数 + /// + /// 繁体字符串 + /// 简体字符串 + public string cht_to_chs(string src) + { + appWord.Selection.Delete(); + appWord.Selection.TypeText(src); + /*UseVariants + Boolean + Optional Boolean. True if Word uses Taiwan, Hong Kong SAR, and Macao SAR character variants. Can only be used if translating from Simplified Chinese to Traditional Chinese*/ + appWord.Selection.Range.TCSCConverter(WdTCSCConverterDirection.wdTCSCConverterDirectionTCSC, true, false); + appWord.ActiveDocument.Select(); + return appWord.Selection.Text; + } + } +} diff --git a/ChineseSubtitleConversionTool/WordApplicationPool.cs b/ChineseSubtitleConversionTool/WordApplicationPool.cs new file mode 100644 index 0000000..15669ae --- /dev/null +++ b/ChineseSubtitleConversionTool/WordApplicationPool.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Threading; + +namespace ChineseSubtitleConversionTool +{ + public static class WordApplicationPool + { + private static readonly SemaphoreSlim semaphore = new SemaphoreSlim(0,Environment.ProcessorCount);//控制数量 + private static readonly Queue pool = new Queue(); + public static bool CreatingWordApplication = false;//用于中断word应用创建 + + //用户选择高精度时就参加一个word放入池中 + public static void InitPool() + { + if (pool.Count == 0) + { + CreateWordApplicationAsync(1); + } + } + /// + /// 异步创建word + /// + /// 要创建的数量 + public static void CreateWordApplicationAsync(int num) + { + CreatingWordApplication = true; + System.Threading.Tasks.Task.Factory.StartNew(() => + { + for (int i = 0; i < num; ++i) + { + if(CreatingWordApplication) + { + WordApplication wordApplication = new WordApplication(); + lock (pool) + { + pool.Enqueue(wordApplication); + } + semaphore.Release(); + } + } + }); + } + /// + /// 根据文件数初始化word,最高不超过系统线程数,生成一个word释放一个信号,不阻塞线程 + /// + /// + public static void InitSemaphore(int num) + { + if (num > 0) + { + int limitSemaphore = Environment.ProcessorCount - semaphore.CurrentCount; + if (limitSemaphore == 0) + { + return; + } + if (num > semaphore.CurrentCount) + { + int releaseNum = 0; + if(num <= Environment.ProcessorCount) + { + releaseNum = num - semaphore.CurrentCount; + } + else if (num > Environment.ProcessorCount) + { + releaseNum = limitSemaphore; + } + CreateWordApplicationAsync(releaseNum); + } + + } + } + /// + /// 获取word + /// + /// + public static WordApplication Get() + { + semaphore.Wait(); + + lock (pool) + { + if (pool.Count > 0) + { + return pool.Dequeue(); + } + } + return new WordApplication();//正常情況不会在这里创建WordApplication() + } + /// + /// 归还word + /// + /// + public static void Return(WordApplication obj) + { + lock (pool) + { + pool.Enqueue(obj); + } + semaphore.Release(); + } + } +} diff --git a/ChineseSubtitleConversionTool/bin/Debug/ChineseSubtitleConversionTool.exe b/ChineseSubtitleConversionTool/bin/Debug/ChineseSubtitleConversionTool.exe index bfcc689..dafc39e 100644 Binary files a/ChineseSubtitleConversionTool/bin/Debug/ChineseSubtitleConversionTool.exe and b/ChineseSubtitleConversionTool/bin/Debug/ChineseSubtitleConversionTool.exe differ