// 截图翻译 private void ScreenTran() { string from = "en", src, dst = null; Image captureImage = default; FrmScreenShot shot = new FrmScreenShot(); SetStateDelegate setState = new SetStateDelegate(MinimizeWindow); try { // 截图翻译并显示 if (tranMode == TranMode.TranAndShowText) { this.Invoke((EventHandler) delegate { setState(true); }); Thread.Sleep(200); // 如果是固定区域翻译(isFixedScreen = true则视为固定区域翻译) if (isFixedScreen == true) { captureImage = FixedScreen(); } else { shot.CopyScreen(); if (shot.ShowDialog() == DialogResult.Cancel) // 显示截图窗口 { return; } captureImage = shot.CaptureImage; } // 翻译模式isEnToZh=true为英译中,false为俄译中 if (isEnToZh == false) { from = "ru"; } // sourceOfTran有“有道”两字使用有道翻译,否则使用百度翻译 if (sourceOfTran.IndexOf("有道") != -1) { Youdao.YoudaoTran(null, from, "zh-CHS", out src, out dst, captureImage); } else { Baidu.BaiduTran(captureImage, from, out src, out dst); } if (copySourceTextToClip) { Clipboard.SetText(src);// 复制原文到剪切板 } if (copyDestTextToClip) { Clipboard.SetText(dst);// 复制译文到剪切板 } if (isSpeak) { SpeechSynthesizer speech = new SpeechSynthesizer(); speech.Rate = 3; // 语速 speech.SpeakAsync(dst); } } else { dst = showCont; } // 不为空 if (!string.IsNullOrEmpty(dst)) { ShowText(dst); } } catch (Exception ex) { if (ex.GetType().FullName == "System.Threading.ThreadAbortException") { return; } // 显示错误 ShowText("错误:" + ex.Message); } finally { if (shot != null && !shot.IsDisposed) { shot.Dispose(); } //if (captureImage != null) // captureImage.Dispose(); } }
// 翻译 private string Translate(bool sendToWindow) { try { if (textBox1_Source.Text == "") { return(""); } if (comboBox2_DestLang.SelectedItem.ToString() != "不翻译") { if (sourceOfTran.IndexOf("有道") != -1) { from = "zh-CHS"; Youdao.YoudaoTran(textBox1_Source.Text, from, Youdao_to[comboBox2_DestLang.SelectedIndex], out src, out dst); } else { from = "zh"; Baidu.Translate(textBox1_Source.Text, from, Baidu_to[comboBox2_DestLang.SelectedIndex], out src, out dst); } } else { dst = textBox1_Source.Text; } // 保存当前选项 FrmMain.TranDestLang = comboBox2_DestLang.SelectedIndex; FrmMain.AutoPressKey = comboBox1_SourceLang.SelectedIndex; FrmMain.AutoSend = checkBox1_AutoSend.Checked; if (!sendToWindow) // 不将译文发送到窗口 { return(dst); } this.WindowState = FormWindowState.Minimized; // 查找窗口句柄 IntPtr hwnd = FindWindowHandle(); // 激活窗口 if (!Api.SetForegroundWindow(hwnd)) { throw new Exception("无法激活窗口!"); } Thread.Sleep(500); KeyBoard(Key[comboBox1_SourceLang.SelectedIndex]); Thread.Sleep(500); SendKeys.SendWait(dst); // SendKeys.Send(dst); // 输入要发送的内容 Thread.Sleep(1000); if (checkBox1_AutoSend.Checked) // 自动发送(按下回车键) { KeyBoard(Keys.Enter); } } catch (Exception ex) { MessageBox.Show(ex.Message, "翻译", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (sendToWindow) // 如果是不将译文发送到窗口,则不会关闭本窗口 { this.Close(); } } return(dst); }