Слияние кода завершено, страница обновится автоматически
using Microsoft.Win32;
using SettingsControl;
using System.Text;
using System.Web;
using System.Security.Cryptography;
using System.Text.Json.Nodes;
using System.Data;
namespace ElyTranslator
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
//translationStatus记录每一行的翻译状态,0是未编辑显示黑色,1是已确认汉化显示绿色,2机翻和匹配旧版汉化显示蓝色,3未匹配到字段显示红色
List<int> sTranslationStatus = [];
List<string> sInternalName = [];
List<string> sOriginText = [];
List<string> sTranslatedText = [];
List<string> sSection = [];
List<string> sInternalNamePre = [];
List<string> sOriginTextPre = [];
List<string> sSectionPre = [];
string nSection = "";
public static string mSendMessage = "提示";
public static Point Loc = new Point(0, 0);
DataTable tc = new();
DataTable tt = new();
DataTable ti = new();
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
Settings.SetValue("Settings", "Location", Location.X.ToString() + "," + Location.Y.ToString());
Settings.SetValue("Settings", "Size", Width.ToString() + "," + Height.ToString());
}
private void MainForm_Load(object sender, EventArgs e)
{
tc.Columns.Add("namecn", typeof(string));
tc.Columns.Add("nameid", typeof(string));
tc.Rows.Add("自动", "auto");
tc.Rows.Add("中文", "zh");
tc.Rows.Add("英语", "en");
tc.Rows.Add("日语", "jp");
tc.Rows.Add("韩语", "kor");
tc.Rows.Add("粤语", "yue");
tc.Rows.Add("文言文", "wyw");
tc.Rows.Add("繁中", "cht");
tc.Rows.Add("法语", "fra");
tc.Rows.Add("西班牙语", "spa");
tc.Rows.Add("俄语", "ru");
tc.Rows.Add("葡萄牙语", "pt");
tc.Rows.Add("德语", "de");
tc.Rows.Add("意大利语", "it");
tc.Rows.Add("希腊语", "el");
tc.Rows.Add("荷兰语", "nl");
tc.Rows.Add("波兰语", "pl");
tc.Rows.Add("保加利亚语", "bul");
tc.Rows.Add("爱沙尼亚语", "est");
tc.Rows.Add("丹麦语", "dan");
tc.Rows.Add("芬兰语", "fin");
tc.Rows.Add("捷克语", "cs");
tc.Rows.Add("罗马尼亚语", "rom");
tc.Rows.Add("斯洛文尼亚语", "slo");
tc.Rows.Add("瑞典语", "swe");
tc.Rows.Add("匈牙利语", "hu");
tc.Rows.Add("越南语", "vie");
fComboBox.DisplayMember = "namecn";
fComboBox.ValueMember = "nameid";
fComboBox.DataSource = tc;
tt = tc.Copy();
tComboBox.DisplayMember = "namecn";
tComboBox.ValueMember = "nameid";
tComboBox.DataSource = tt;
ti.Columns.Add("namecn", typeof(string));
ti.Columns.Add("time", typeof(string));
ti.Rows.Add("基础版", "1000");
ti.Rows.Add("高级版", "100");
ti.Rows.Add("尊享版", "10");
bTransInterval.DisplayMember = "namecn";
bTransInterval.ValueMember = "time";
bTransInterval.DataSource = ti;
string transf = Settings.GetValue("Settings", "TransFrom");
if (!int.TryParse(transf, out int codef))
fComboBox.SelectedIndex = 2;
else
fComboBox.SelectedIndex = codef;
string transt = Settings.GetValue("Settings", "TransTo");
if (!int.TryParse(transt, out int codet))
tComboBox.SelectedIndex = 1;
else
tComboBox.SelectedIndex = codet;
string transi = Settings.GetValue("Settings", "Interval");
if (!int.TryParse(transi, out int codei))
tComboBox.SelectedIndex = 1;
else
bTransInterval.SelectedIndex = codei;
string mLoc = Settings.GetValue("Settings", "Location");
if (!string.IsNullOrEmpty(mLoc) && mLoc.Contains(','))
{
string stringx = mLoc[..mLoc.IndexOf(',')];
string stringy = mLoc[(mLoc.IndexOf(',') + 1)..];
if (int.TryParse(stringx, out int x) && int.TryParse(stringy, out int y))
Location = new Point(x, y);
}
string mSize = Settings.GetValue("Settings", "Size");
if (!string.IsNullOrEmpty(mSize) && mSize.Contains(','))
{
string stringx = mSize[..mSize.IndexOf(',')];
string stringy = mSize[(mSize.IndexOf(',') + 1)..];
if (int.TryParse(stringx, out int x) && int.TryParse(stringy, out int y))
{
Width = x;
Height = y;
}
}
}
private void MainForm_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F5)
{
bBaiduTranslateBtn_Click(sender, e);
e.Handled = true;
}
}
#region 文件操作
private void loadEnFileBtn_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new();
openFileDialog.Title = "打开英文文件";
openFileDialog.Filter = "游戏文件|*.cfg";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
tListBox.Items.Clear();
sInternalName.Clear();
sOriginText.Clear();
sTranslatedText.Clear();
sSection.Clear();
sTranslationStatus.Clear();
sInternalNamePre.Clear();
sOriginTextPre.Clear();
sSectionPre.Clear();
nSection = "";
if (filePath.EndsWith(".cfg", StringComparison.OrdinalIgnoreCase))
openCFGFile(filePath, true);
tPreFileBtn.Enabled = true;
tSaveFileBtn.Enabled = true;
}
}
private void tPreFileBtn_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new();
openFileDialog.Title = "打开旧版汉化";
openFileDialog.Filter = "游戏文件|*.cfg";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
tListBox.Items.Clear();
sInternalNamePre.Clear();
sOriginTextPre.Clear();
sSectionPre.Clear();
nSection = "";
if (filePath.EndsWith(".cfg", StringComparison.OrdinalIgnoreCase))
openCFGFile(filePath, false);
}
}
private void openCFGFile(string filePath, bool load)
{
string[]? data = File.ReadAllLines(filePath);
for (int i = 0; i < data.Length; i++)
{
if (string.IsNullOrEmpty(data[i]) || data[i][0] == '#')
formatString(data[i], load);
else if (data[i][0] == '[' && data[i][data[i].Length - 1] == ']')
{
nSection = data[i];
formatString(data[i], load);
}
else if (data[i].Contains("="))
{
int loc = data[i].IndexOf("=");
if (loc > 0)
{
if (load)
{
sInternalName.Add(data[i].Substring(0, loc));
sOriginText.Add(data[i].Substring(loc + 1, data[i].Length - loc - 1));
sTranslatedText.Add(data[i].Substring(loc + 1, data[i].Length - loc - 1));
sSection.Add(nSection);
sTranslationStatus.Add(0);
}
else
{
sInternalNamePre.Add(data[i].Substring(0, loc));
sOriginTextPre.Add(data[i].Substring(loc + 1, data[i].Length - loc - 1));
sSectionPre.Add(nSection);
}
}
else
formatString(data[i], load);
}
else
formatString(data[i], load);
}
if (!load)
setStatus();
loadListBox();
}
private void formatString(string data, bool load)
{
if (load)
{
sInternalName.Add(data);
sOriginText.Add("");
sTranslatedText.Add("");
sSection.Add("#");
sTranslationStatus.Add(0);
}
else
{
sInternalNamePre.Add(data);
sOriginTextPre.Add("");
sSectionPre.Add("#");
}
}
private void setStatus()
{
for (int i = 0; i < sInternalName.Count; i++)
{
sTranslationStatus[i] = 3;
for (int j = 0; j < sInternalNamePre.Count; j++)
{
if (sInternalName[i].Equals(sInternalNamePre[j]) && sSection[i].Equals(sSectionPre[j]))
{
if (sTranslatedText[i].Equals(sOriginTextPre[j]))
sTranslationStatus[i] = 0;
else
{
sTranslationStatus[i] = 2;
sTranslatedText[i] = sOriginTextPre[j];
}
break;
}
}
}
}
private void tSaveFileBtn_Click(object sender, EventArgs e)
{
//保存TXT文件
string[]? save = new string[sInternalName.Count];
for (int i = 0; i < sInternalName.Count; i++)
{
if (sSection[i] == "#")
save[i] = sInternalName[i];
else
save[i] = sInternalName[i] + "=" + sTranslatedText[i];
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "保存CFG文件";
saveFileDialog.Filter = "游戏文件|*.cfg";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
File.WriteAllLines(saveFileDialog.FileName, save);
MessageBoxEXEC("保存成功");
}
}
#endregion
#region ListBox功能
private void loadListBox()
{
Graphics g = tListBox.CreateGraphics();
int hzSize;
for (int i = 0; i < sInternalName.Count; i++)
{
if (sSection[i] == "#")
tListBox.Items.Add(sInternalName[i]);
else
tListBox.Items.Add(sInternalName[i] + "=" + sTranslatedText[i]);
hzSize = (int)g.MeasureString(tListBox.Items[i].ToString(), tListBox.Font).Width;
if (hzSize > tListBox.HorizontalExtent)
tListBox.HorizontalExtent = hzSize;
tProgressBar.Value = i * 100 / sInternalName.Count;
}
tProgressBar.Value = 0;
g.Dispose();
}
private void tListBox_DrawItem(object sender, DrawItemEventArgs e)
{
//自绘ListBox,实现不同颜色的字体
e.DrawBackground();
if (e.Index < 0)
return;
if (e.Index >= sTranslationStatus.Count)
return;
string? drawListBoxStr = tListBox.Items[e.Index].ToString();
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
e.Graphics.DrawString(drawListBoxStr, tListBox.Font, Brushes.White, e.Bounds);
else
{
switch (sTranslationStatus[e.Index])
{
case 0:
e.Graphics.DrawString(drawListBoxStr, tListBox.Font, Brushes.Black, e.Bounds);
break;
case 1:
e.Graphics.DrawString(drawListBoxStr, tListBox.Font, Brushes.Green, e.Bounds);
break;
case 2:
e.Graphics.DrawString(drawListBoxStr, tListBox.Font, Brushes.Blue, e.Bounds);
break;
case 3:
e.Graphics.DrawString(drawListBoxStr, tListBox.Font, Brushes.Red, e.Bounds);
break;
default:
e.Graphics.DrawString(drawListBoxStr, tListBox.Font, Brushes.Black, e.Bounds);
break;
}
}
}
private void tListBox_SelectedIndexChanged(object sender, EventArgs e)
{
int sIndex = tListBox.SelectedIndex;
if (tListBox.SelectedItems.Count == 1)
{
eOriginTextBox.Text = "原文:" + sOriginText[sIndex];
eTranslateTextBox.Text = sTranslatedText[sIndex];
eRowLabel.Text = "第" + (sIndex + 1).ToString() + "行";
eInteralNameLabel.Text = "字段:" + sInternalName[sIndex];
eTranslateTextBox.Focus();
eTranslateTextBox.Select(eTranslateTextBox.Text.Length, 0);
}
}
#endregion
#region 其他功能
void MessageBoxEXEC(string send)
{
mSendMessage = send;
MyMessageBox.MessageBoxEX messageBoxEX = new MyMessageBox.MessageBoxEX();
Loc = new Point(Location.X - 220 + Width / 2, Location.Y - 130 + Height / 2);
messageBoxEX.ShowDialog();
}
private void eConfirmBtn_Click(object sender, EventArgs e)
{
tConfirmFuc();
}
private void fCopyBtn_Click(object sender, EventArgs e)
{
//复制原文按钮,把原文内容复制到剪贴板
if (tListBox.SelectedItems.Count == 1)
{
Clipboard.SetDataObject(sOriginText[tListBox.SelectedIndex]);
}
}
private void tConfirmFuc()
{
//确认翻译函数,把编辑框的数据存入translatedText
if (tListBox.SelectedItems.Count == 1)
{
int index = tListBox.SelectedIndex;
sTranslatedText[index] = eTranslateTextBox.Text;
sTranslationStatus[index] = 1;
tListBox.Items[index] = sInternalName[index] + "=" + sTranslatedText[index];
if (index + 1 < tListBox.Items.Count)
tListBox.SetSelected(index + 1, true);
}
}
private void bExitBtn_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void bAboutBtn_Click(object sender, EventArgs e)
{
MyAboutBox.MyAbout myAbout = new MyAboutBox.MyAbout();
Loc = new Point(Location.X - 188 + Width / 2, Location.Y - 72 + Height / 2);
myAbout.ShowDialog();
}
#endregion
#region 搜索功能
private void sSearchFuc()
{
//搜索功能,在字段,原文和译文中搜索
if (sInternalName.Count > 0 && !string.IsNullOrEmpty(sSearchTextBox.Text))
{
int loc;
if (tListBox.SelectedItems.Count == 1)
loc = tListBox.SelectedIndex + 1;
else
loc = 0;
string search = sSearchTextBox.Text.ToLower();
for (int i = loc; i < sInternalName.Count; i++)
{
if (sInternalName[i].ToLower().Contains(search) || sOriginText[i].ToLower().Contains(search) || sTranslatedText[i].ToLower().Contains(search))
{
if (i < tListBox.Items.Count)
{
tListBox.SelectedIndex = i;
sSearchTextBox.Focus();
sSearchTextBox.Select(sSearchTextBox.Text.Length, 0);
return;
}
}
}
MessageBoxEXEC("搜索完毕,下文中未找到:" + search);
}
else
MessageBoxEXEC("未加载文本或遇到BUG");
}
private void sSearchBtn_Click(object sender, EventArgs e)
{
sSearchFuc();
}
private void sReplaceBtn_Click(object sender, EventArgs e)
{
tReplacePanel.BringToFront();
tReplacePanel.Visible = true;
}
private void sReverseSearchBtn_Click(object sender, EventArgs e)
{
//反向搜索
if (sInternalName.Count > 0 && !string.IsNullOrEmpty(sSearchTextBox.Text))
{
int loc;
if (tListBox.SelectedItems.Count == 1)
loc = tListBox.SelectedIndex - 1;
else
loc = tListBox.Items.Count - 1;
string search = sSearchTextBox.Text.ToLower();
for (int i = loc; i > -1; i--)
{
if (sInternalName[i].ToLower().Contains(search) || sOriginText[i].ToLower().Contains(search) || sTranslatedText[i].ToLower().Contains(search))
{
if (i < tListBox.Items.Count)
{
tListBox.SelectedIndex = i;
sSearchTextBox.Focus();
sSearchTextBox.Select(sSearchTextBox.Text.Length, 0);
return;
}
}
}
MessageBoxEXEC("搜索完毕,上文中未找到:" + search);
}
else
MessageBoxEXEC("未加载文本或遇到BUG");
}
#endregion
#region 替换功能
private void rReplaceSearchBtn_Click(object sender, EventArgs e)
{
//替换框搜索按钮
if (tListBox.Items.Count < 1)
{
MessageBoxEXEC("未加载汉化文件或出错");
return;
}
if (string.IsNullOrEmpty(rReplaceFrom.Text))
{
MessageBoxEXEC("请输入要替换的文本");
return;
}
int loc;
if (tListBox.SelectedItems.Count == 1)
loc = tListBox.SelectedIndex;
else
loc = 0;
if (!rReplaceSearchFuc(loc))
MessageBoxEXEC("向下搜索完毕,找不到:" + rReplaceFrom.Text);
}
private void rReplaceBtn_Click(object sender, EventArgs e)
{
//单行替换
if (tListBox.Items.Count < 1)
{
MessageBoxEXEC("未加载汉化文件或出错");
return;
}
if (string.IsNullOrEmpty(rReplaceFrom.Text))
{
MessageBoxEXEC("请输入要替换的文本");
return;
}
if (tListBox.SelectedItems.Count == 1)
{
if (rReplaceFuc(tListBox.SelectedIndex))
return;
else
{
if (rReplaceSearchFuc(tListBox.SelectedIndex))
rReplaceFuc(tListBox.SelectedIndex);
else
MessageBoxEXEC("搜索完毕,下文中未找到:" + rReplaceFrom.Text);
}
}
else
{
if (rReplaceSearchFuc(tListBox.SelectedIndex + 1))
rReplaceFuc(tListBox.SelectedIndex);
else
MessageBoxEXEC("搜索完毕,下文中未找到:" + rReplaceFrom.Text);
}
}
private void rReplaceAllBtn_Click(object sender, EventArgs e)
{
//全部替换
if (tListBox.Items.Count < 1)
{
MessageBoxEXEC("未加载汉化文件或出错");
return;
}
if (string.IsNullOrEmpty(rReplaceFrom.Text))
{
MessageBoxEXEC("请输入要替换的文本");
return;
}
int i = 0;
while (rReplaceSearchFuc(i))
{
i = tListBox.SelectedIndex;
if (rReplaceFuc(i) && i + 1 < tListBox.Items.Count)
i++;
}
MessageBoxEXEC("全部替换完成");
}
private void rReplaceClose_Click(object sender, EventArgs e)
{
tReplacePanel.SendToBack();
tReplacePanel.Visible = false;
}
private bool rReplaceSearchFuc(int index)
{
if (sInternalName.Count > 0 && !string.IsNullOrEmpty(rReplaceFrom.Text))
{
string search = rReplaceFrom.Text.ToLower();
for (int i = index; i < sInternalName.Count; i++)
{
if (sTranslatedText[i].ToLower().Contains(search))
{
tListBox.SelectedIndex = i;
return true;
}
}
return false;
}
else
return false;
}
private bool rReplaceFuc(int index)
{
if (sSection[index] != "#" && !string.IsNullOrEmpty(sTranslatedText[index]))
{
if (sTranslatedText[index].Contains(rReplaceFrom.Text))
{
sTranslatedText[index] = sTranslatedText[index].Replace(rReplaceFrom.Text, rReplaceTo.Text);
sTranslationStatus[index] = 1;
tListBox.Items[index] = sInternalName[index] + "=" + sTranslatedText[index];
return true;
}
else
return false;
}
else
return false;
}
#endregion
#region 键盘事件
private void eTranslateTextBox_KeyUp(object sender, KeyEventArgs e)
{
//截获回车确认翻译,截获上下按钮变为换行功能
if (e.KeyCode == Keys.Enter)
{
tConfirmFuc();
}
if (e.KeyCode == Keys.Up)
{
if (tListBox.SelectedIndex > 0)
tListBox.SetSelected(tListBox.SelectedIndex - 1, true);
}
if (e.KeyCode == Keys.Down)
{
if (tListBox.SelectedIndex < tListBox.Items.Count - 1)
tListBox.SetSelected(tListBox.SelectedIndex + 1, true);
}
}
private void eTranslateTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
//处理回车消息,否则会有错误提示音
if (e.KeyChar == '\r')
{
e.Handled = true;
}
}
private void eTranslateTextBox_KeyDown(object sender, KeyEventArgs e)
{
//截获上下按钮使其不移动光标
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
{
e.Handled = true;
}
}
private void sSearchTextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
sSearchFuc();
}
}
private void sSearchTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
e.Handled = true;
}
}
private void eLongTranslate_KeyUp(object sender, KeyEventArgs e)
{
//长行确认翻译并关闭长行页面
if (e.KeyCode == Keys.Enter)
{
eTranslateTextBox.Text = eLongTranslate.Text;
tConfirmFuc();
eLongLinePanel.SendToBack();
eLongLinePanel.Visible = false;
}
}
private void eLongTranslate_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
e.Handled = true;
}
}
private void bTransInterval_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)8 && e.KeyChar != (char)46 && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
private void bTransFromTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)8 && e.KeyChar != (char)46 && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
private void bTransToTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)8 && e.KeyChar != (char)46 && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
#endregion
#region 长行处理
private void eLongLineBtn_Click(object sender, EventArgs e)
{
if (tListBox.SelectedItems.Count == 1)
{
eLongRow.Text = eRowLabel.Text;
eLongInternalName.Text = eInteralNameLabel.Text;
eLongOrigin.Text = eOriginTextBox.Text;
eLongTranslate.Text = eTranslateTextBox.Text;
eLongLinePanel.BringToFront();
eLongLinePanel.Visible = true;
}
else
{
MessageBoxEXEC("请先选中要编辑的行。");
}
}
private void eLongConfirmBtn_Click(object sender, EventArgs e)
{
eTranslateTextBox.Text = eLongTranslate.Text;
tConfirmFuc();
eLongLinePanel.SendToBack();
eLongLinePanel.Visible = false;
}
private void eLongClose_Click(object sender, EventArgs e)
{
eLongLinePanel.SendToBack();
eLongLinePanel.Visible = false;
}
#endregion
#region 百度翻译
private void bOKBtn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(bAPPIDTextBox.Text) || string.IsNullOrEmpty(bSecretKeyTextBox.Text))
MessageBoxEXEC("请输入APP ID和密钥");
else
{
string appid = Convert.ToBase64String(Encoding.UTF8.GetBytes(bAPPIDTextBox.Text));
string secretkey = Convert.ToBase64String(Encoding.UTF8.GetBytes(bSecretKeyTextBox.Text));
Settings.SetValue("Baidu", "APPID", appid);
Settings.SetValue("Baidu", "SecretKey", secretkey);
bBaiduPanel.SendToBack();
bBaiduPanel.Visible = false;
}
string transcode = fComboBox.SelectedIndex.ToString();
if (!string.IsNullOrEmpty(transcode))
Settings.SetValue("Settings", "TransFrom", transcode!);
transcode = tComboBox.SelectedIndex.ToString();
if (!string.IsNullOrEmpty(transcode))
Settings.SetValue("Settings", "TransTo", transcode!);
transcode = bTransInterval.SelectedIndex.ToString();
if (!string.IsNullOrEmpty(transcode))
Settings.SetValue("Settings", "Interval", transcode!);
}
private void bCancelBtn_Click(object sender, EventArgs e)
{
bBaiduPanel.SendToBack();
bBaiduPanel.Visible = false;
}
private void bBaiduAPIBtn_Click(object sender, EventArgs e)
{
string appid = Settings.GetValue("Baidu", "APPID");
string secretkey = Settings.GetValue("Baidu", "SecretKey");
if (!string.IsNullOrEmpty(appid) && !string.IsNullOrEmpty(secretkey))
{
appid = Encoding.UTF8.GetString(Convert.FromBase64String(appid));
secretkey = Encoding.UTF8.GetString(Convert.FromBase64String(secretkey));
bAPPIDTextBox.Text = appid;
bSecretKeyTextBox.Text = secretkey;
}
bBaiduPanel.Location = new Point(Width / 2 - 240, Height / 2 - 240);
bBaiduPanel.BringToFront();
bBaiduPanel.Visible = true;
}
private void bBaiduTranslateBtn_Click(object sender, EventArgs e)
{
if (tListBox.SelectedItems.Count == 1)
{
int index = tListBox.SelectedIndex;
string appid = Settings.GetValue("Baidu", "APPID");
string secretkey = Settings.GetValue("Baidu", "SecretKey");
if (string.IsNullOrEmpty(appid) && string.IsNullOrEmpty(secretkey))
{
MessageBoxEXEC("请先设置APP ID和密钥");
return;
}
appid = Encoding.UTF8.GetString(Convert.FromBase64String(appid));
secretkey = Encoding.UTF8.GetString(Convert.FromBase64String(secretkey));
// 源语言
string from = fComboBox.SelectedValue!.ToString()!;
if (string.IsNullOrEmpty(from))
from = "en";
// 目标语言
string to = tComboBox.SelectedValue!.ToString()!;
if (string.IsNullOrEmpty(to))
to = "zh";
string translated = bBaiduTranslate(sOriginText[index], appid, secretkey, from, to);
if (translated.Contains("error_code"))
{
JsonNode? error = JsonNode.Parse(translated);
MessageBoxEXEC("错误代码:" + error!["error_code"]!.GetValue<string>() + "\n错误信息:" + error!["error_msg"]!.GetValue<string>());
return;
}
if (translated.Contains("trans_result") && translated.Contains("dst"))
{
JsonNode? node = JsonNode.Parse(translated);
JsonArray trans = node!["trans_result"]!.AsArray();
if (trans.Count == 1)
{
JsonNode transNode = trans[0]!;
string result = transNode["dst"]!.GetValue<string>();
sTranslatedText[index] = result;
tListBox.Items[index] = sInternalName[index] + "=" + sTranslatedText[index];
sTranslationStatus[index] = 2;
tListBox.SetSelected(index, true);
}
}
else
MessageBoxEXEC("未知错误");
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
RegistryKey? key = Registry.ClassesRoot.OpenSubKey(@"http\shell\open\command\");
string? app = key!.GetValue("")!.ToString();
if (!string.IsNullOrEmpty(app))
{
if (app.Contains(".exe\""))
{
int loc = app.LastIndexOf(".exe\"");
app = app.Substring(0, loc + 5);
System.Diagnostics.Process.Start(app, "https://api.fanyi.baidu.com/");
}
else if (app.Contains(".exe"))
{
int loc = app.LastIndexOf(".exe");
app = app.Substring(0, loc + 4);
System.Diagnostics.Process.Start(app, "https://api.fanyi.baidu.com/");
}
else
{
Clipboard.SetDataObject("https://api.fanyi.baidu.com/");
MessageBoxEXEC("网址:https://api.fanyi.baidu.com/已复制到剪贴板,请用浏览器打开");
}
}
else
{
Clipboard.SetDataObject("https://api.fanyi.baidu.com/");
MessageBoxEXEC("网址:https://api.fanyi.baidu.com/已复制到剪贴板,请用浏览器打开");
}
}
catch (Exception ex)
{
MessageBoxEXEC("遇到错误:" + ex.Message);
}
}
private string bBaiduTranslate(string q, string appId, string secretKey, string from, string to)
{
Random rd = new Random();
string salt = rd.Next(100000).ToString();
string sign = EncryptString(appId + q + salt + secretKey);
string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
url += "q=" + HttpUtility.UrlEncode(q);
url += "&from=" + from;
url += "&to=" + to;
url += "&appid=" + appId;
url += "&salt=" + salt;
url += "&sign=" + sign;
HttpHelper.HttpClientService httpService = HttpHelper.HttpClientService.GetInstance();
string retString = httpService.HttpGet(url);
return retString;
}
public static string EncryptString(string str)
{
// 计算MD5值
MD5 md5 = MD5.Create();
// 将字符串转换成字节数组
byte[] byteOld = Encoding.UTF8.GetBytes(str);
// 调用加密方法
byte[] byteNew = md5.ComputeHash(byteOld);
// 将加密结果转换为字符串
StringBuilder sb = new StringBuilder();
foreach (byte b in byteNew)
{
// 将字节转换成16进制表示的字符串,
sb.Append(b.ToString("x2"));
}
// 返回加密的字符串
return sb.ToString();
}
private void bBaiduTransMultiBtn_Click(object sender, EventArgs e)
{
tProgressBar.Value = 0;
if (sInternalName.Count > 0)
{
if (!int.TryParse(bTransFromTextBox.Text, out int from))
{
MessageBoxEXEC("请输入正确的起止行");
return;
}
if (!int.TryParse(bTransToTextBox.Text, out int to))
{
MessageBoxEXEC("请输入正确的起止行");
return;
}
if(from >= to)
{
MessageBoxEXEC("起始行应小于终止行");
return;
}
string appid = Settings.GetValue("Baidu", "APPID");
string secretkey = Settings.GetValue("Baidu", "SecretKey");
if (string.IsNullOrEmpty(appid) && string.IsNullOrEmpty(secretkey))
{
MessageBoxEXEC("请先设置APP ID和密钥");
return;
}
if (!int.TryParse(bTransInterval.SelectedValue!.ToString(), out int time))
{
time = 1000;
}
appid = Encoding.UTF8.GetString(Convert.FromBase64String(appid));
secretkey = Encoding.UTF8.GetString(Convert.FromBase64String(secretkey));
// 源语言
string tfrom = fComboBox.SelectedValue!.ToString()!;
if (string.IsNullOrEmpty(tfrom))
tfrom = "en";
// 目标语言
string tto = tComboBox.SelectedValue!.ToString()!;
if (string.IsNullOrEmpty(tto))
tto = "zh";
for (int i = from - 1; i < to; i++)
{
string translated = bBaiduTranslate(sOriginText[i], appid, secretkey, tfrom, tto);
if (translated.Contains("error_code"))
{
JsonNode? error = JsonNode.Parse(translated);
MessageBoxEXEC("错误代码:" + error!["error_code"]!.GetValue<string>() + "\n错误信息:" + error!["error_msg"]!.GetValue<string>());
return;
}
if (translated.Contains("trans_result") && translated.Contains("dst"))
{
JsonNode? node = JsonNode.Parse(translated);
JsonArray trans = node!["trans_result"]!.AsArray();
if (trans.Count == 1)
{
JsonNode transNode = trans[0]!;
string result = transNode["dst"]!.GetValue<string>();
sTranslatedText[i] = result;
sTranslationStatus[i] = 2;
tListBox.Items[i] = sInternalName[i] + "=" + sTranslatedText[i];
tListBox.SetSelected(i, true);
}
}
else
MessageBoxEXEC("未知错误");
tProgressBar.Value = (i - from + 1) * 100 / (to - from);
Thread.Sleep(time);
}
tProgressBar.Value = 0;
MessageBoxEXEC("批量翻译结束");
}
}
#endregion
}
}
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Опубликовать ( 0 )