需要的朋友可以下载,这几天看到园子里有几个兄弟编写Google的在线翻译;
我也凑一下热闹,网络收集了些资源,自己重新加工了一下,希望能对园子里的朋友有用。
功能:支持简体中文、法语、德语、意大利语、西班牙玉,葡萄牙语;
大家可以根据自己的需要扩充。
采用 Microsoft Visual Studio 2008设计,需要3.5运行库。
我也凑一下热闹,网络收集了些资源,自己重新加工了一下,希望能对园子里的朋友有用。
功能:支持简体中文、法语、德语、意大利语、西班牙玉,葡萄牙语;
大家可以根据自己的需要扩充。
采用 Microsoft Visual Studio 2008设计,需要3.5运行库。
资源类:
/* •————————————————————————————————•
| Email:[email protected] |
| amend:Gordon(高阳) |
| 2008.4.14 |
•————————————————————————————————• */
| Email:[email protected] |
| amend:Gordon(高阳) |
| 2008.4.14 |
•————————————————————————————————• */
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
namespace RavSoft
{
///
/// A framework to expose information rendered by a URL (i.e. a "web
/// resource") as an object that can be manipulated by an application.
/// You use WebResourceProvider by deriving from it and implementing
/// getFetchUrl() and optionally overriding other methods.
///
abstract public class WebResourceProvider
{
///
/// Default constructor.
///
public WebResourceProvider()
{
reset();
}
{
///
/// A framework to expose information rendered by a URL (i.e. a "web
/// resource") as an object that can be manipulated by an application.
/// You use WebResourceProvider by deriving from it and implementing
/// getFetchUrl() and optionally overriding other methods.
///
abstract public class WebResourceProvider
{
///
/// Default constructor.
///
public WebResourceProvider()
{
reset();
}
/////////////
// Properties
// Properties
///
/// Gets and sets the user agent string.
///
public string Agent
{
get
{ return m_strAgent; }
set
{ m_strAgent = (value == null ? "" : value); }
}
/// Gets and sets the user agent string.
///
public string Agent
{
get
{ return m_strAgent; }
set
{ m_strAgent = (value == null ? "" : value); }
}
///
/// Gets and sets the referer string.
///
public string Referer
{
get
{ return m_strReferer; }
set
{ m_strReferer = (value == null ? "" : value); }
}
/// Gets and sets the referer string.
///
public string Referer
{
get
{ return m_strReferer; }
set
{ m_strReferer = (value == null ? "" : value); }
}
///
/// Gets and sets the minimum pause time interval (in mSec).
///
public int Pause
{
get
{ return m_nPause; }
set
{ m_nPause = value; }
}
/// Gets and sets the minimum pause time interval (in mSec).
///
public int Pause
{
get
{ return m_nPause; }
set
{ m_nPause = value; }
}
///
/// Gets and sets the timeout (in mSec).
///
public int Timeout
{
get
{ return m_nTimeout; }
set
{ m_nTimeout = value; }
}
/// Gets and sets the timeout (in mSec).
///
public int Timeout
{
get
{ return m_nTimeout; }
set
{ m_nTimeout = value; }
}
///
/// Returns the retrieved content.
///
///The content.
public string Content
{
get
{ return m_strContent; }
}
/// Returns the retrieved content.
///
///
public string Content
{
get
{ return m_strContent; }
}
///
/// Gets the fetch timestamp.
///
public DateTime FetchTime
{
get
{ return m_tmFetchTime; }
}
/// Gets the fetch timestamp.
///
public DateTime FetchTime
{
get
{ return m_tmFetchTime; }
}
///
/// Gets the last error message, if any.
///
public string ErrorMsg
{
get
{ return m_strError; }
}
/// Gets the last error message, if any.
///
public string ErrorMsg
{
get
{ return m_strError; }
}
/////////////
// Operations
// Operations
///
/// Resets the state of the object.
///
public void reset()
{
m_strAgent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)";
m_strReferer = "";
m_strError = "";
m_strContent = "";
m_httpStatusCode = HttpStatusCode.OK;
m_nPause = 0;
m_nTimeout = 0;
m_tmFetchTime = DateTime.MinValue;
}
/// Resets the state of the object.
///
public void reset()
{
m_strAgent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)";
m_strReferer = "";
m_strError = "";
m_strContent = "";
m_httpStatusCode = HttpStatusCode.OK;
m_nPause = 0;
m_nTimeout = 0;
m_tmFetchTime = DateTime.MinValue;
}
///
/// Fetches the web resource.
///
public void fetchResource()
{
// Initialize the provider - quit if initialization fails
if (!init())
return;
/// Fetches the web resource.
///
public void fetchResource()
{
// Initialize the provider - quit if initialization fails
if (!init())
return;
// Main loop
bool bOK = false;
do
{
string url = getFetchUrl();
getContent(url);
bOK = (m_httpStatusCode == HttpStatusCode.OK);
if (bOK)
parseContent();
}
while (bOK && continueFetching());
}
bool bOK = false;
do
{
string url = getFetchUrl();
getContent(url);
bOK = (m_httpStatusCode == HttpStatusCode.OK);
if (bOK)
parseContent();
}
while (bOK && continueFetching());
}
//////////////////
// Virtual methods
// Virtual methods
///
/// Provides the derived class with an opportunity to initialize itself.
///
///true if the operation succeeded, false otherwise.
protected virtual bool init()
{ return true; }
/// Provides the derived class with an opportunity to initialize itself.
///
///
protected virtual bool init()
{ return true; }
///
/// Returns the url to be fetched.
///
///The url to be fetched.
abstract protected string getFetchUrl();
/// Returns the url to be fetched.
///
///
abstract protected string getFetchUrl();
///
/// Retrieves the POST data (if any) to be sent to the url to be fetched.
/// The data is returned as a string of the form "arg=val [&arg=val]...".
///
///A string containing the POST data or null if none.
protected virtual string getPostData()
{ return null; }
/// Retrieves the POST data (if any) to be sent to the url to be fetched.
/// The data is returned as a string of the form "arg=val [&arg=val]...".
///
///
protected virtual string getPostData()
{ return null; }
///
/// Provides the derived class with an opportunity to parse the fetched content.
///
protected virtual void parseContent()
{ }
/// Provides the derived class with an opportunity to parse the fetched content.
///
protected virtual void parseContent()
{ }
///
/// Informs the framework that it needs to continue fetching urls.
///
///
/// true if the framework needs to continue fetching urls, false otherwise.
///
protected virtual bool continueFetching()
{ return false; }
/// Informs the framework that it needs to continue fetching urls.
///
///
/// true if the framework needs to continue fetching urls, false otherwise.
///
protected virtual bool continueFetching()
{ return false; }
///////////////////////////
// Implementation (members)
// Implementation (members)
/// User agent string used when making an HTTP request.
string m_strAgent;
string m_strAgent;
/// Referer string used when making an HTTP request.
string m_strReferer;
string m_strReferer;
/// Error message.
string m_strError;
string m_strError;
/// Retrieved.
string m_strContent;
string m_strContent;
/// HTTP status code.
HttpStatusCode m_httpStatusCode;
HttpStatusCode m_httpStatusCode;
/// Minimum number of mSecs to pause between successive HTTP requests.
int m_nPause;
int m_nPause;
/// HTTP request timeout (in mSecs).
int m_nTimeout;
int m_nTimeout;
/// Timestamp of last fetch.
DateTime m_tmFetchTime;
DateTime m_tmFetchTime;
///////////////////////////
// Implementation (methods)
// Implementation (methods)
///
/// Retrieves the content of the url to be fetched.
///
/// Url to be fetched.
void getContent
(string url)
{
// Pause, if necessary
if (m_nPause > 0)
{
int nElapsedMsec = 0;
do
{
/// Retrieves the content of the url to be fetched.
///
/// Url to be fetched.
void getContent
(string url)
{
// Pause, if necessary
if (m_nPause > 0)
{
int nElapsedMsec = 0;
do
{
// Determine the time elapsed since the last fetch (if any)
if (nElapsedMsec == 0)
{
if (m_tmFetchTime != DateTime.MinValue)
{
TimeSpan tsElapsed = m_tmFetchTime - DateTime.Now;
nElapsedMsec = (int)tsElapsed.TotalMilliseconds;
}
}
if (nElapsedMsec == 0)
{
if (m_tmFetchTime != DateTime.MinValue)
{
TimeSpan tsElapsed = m_tmFetchTime - DateTime.Now;
nElapsedMsec = (int)tsElapsed.TotalMilliseconds;
}
}
// Pause 100mSec increment if necessary
int nSleepMsec = 100;
if (nElapsedMsec < m_nPause)
{
Thread.Sleep(nSleepMsec);
nElapsedMsec += nSleepMsec;
}
}
while (nElapsedMsec < m_nPause);
}
int nSleepMsec = 100;
if (nElapsedMsec < m_nPause)
{
Thread.Sleep(nSleepMsec);
nElapsedMsec += nSleepMsec;
}
}
while (nElapsedMsec < m_nPause);
}
// Set up the fetch request
string strUrl = url;
if (!strUrl.StartsWith("http://"))
strUrl = "http://" + strUrl;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl);
req.AllowAutoRedirect = true;
req.UserAgent = m_strAgent;
req.Referer = m_strReferer;
if (m_nTimeout != 0)
req.Timeout = m_nTimeout;
string strUrl = url;
if (!strUrl.StartsWith("http://"))
strUrl = "http://" + strUrl;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl);
req.AllowAutoRedirect = true;
req.UserAgent = m_strAgent;
req.Referer = m_strReferer;
if (m_nTimeout != 0)
req.Timeout = m_nTimeout;
// Add POST data (if present)
string strPostData = getPostData();
if (strPostData != null)
{
string strPostData = getPostData();
if (strPostData != null)
{
ASCIIEncoding asciiEncoding = new ASCIIEncoding();
byte[] postData = asciiEncoding.GetBytes(strPostData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postData.Length;
byte[] postData = asciiEncoding.GetBytes(strPostData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postData.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
reqStream.Close();
}
reqStream.Write(postData, 0, postData.Length);
reqStream.Close();
}
// Fetch the url - return on error
m_strError = "";
m_strContent = "";
HttpWebResponse resp = null;
try
{
m_tmFetchTime = DateTime.Now;
resp = (HttpWebResponse)req.GetResponse();
}
catch (Exception exc)
{
if (exc is WebException)
{
WebException webExc = exc as WebException;
m_strError = webExc.Message;
}
return;
}
finally
{
if (resp != null)
m_httpStatusCode = resp.StatusCode;
}
// Store retrieved contentm_strError = "";
m_strContent = "";
HttpWebResponse resp = null;
try
{
m_tmFetchTime = DateTime.Now;
resp = (HttpWebResponse)req.GetResponse();
}
catch (Exception exc)
{
if (exc is WebException)
{
WebException webExc = exc as WebException;
m_strError = webExc.Message;
}
return;
}
finally
{
if (resp != null)
m_httpStatusCode = resp.StatusCode;
}
try
{
Stream stream = resp.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
m_strContent = streamReader.ReadToEnd();
}
catch (Exception)
{
// Read failure occured - nothing to do
}
}
}
}
调用:
private void OnTranslate(object sender, System.EventArgs e)
{
// Get English text - complain if none
string strEnglish = editEnglish.Text.Trim();
if (strEnglish.Equals(String.Empty))
{
MessageBox.Show("Please enter the text to be translated.",
"GoogleTranslatorForm Demo",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
editEnglish.SelectAll();
editEnglish.Focus();
return;
}
{
// Get English text - complain if none
string strEnglish = editEnglish.Text.Trim();
if (strEnglish.Equals(String.Empty))
{
MessageBox.Show("Please enter the text to be translated.",
"GoogleTranslatorForm Demo",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
editEnglish.SelectAll();
editEnglish.Focus();
return;
}
// Get translation mode
GoogleTranslator.Mode mode = GoogleTranslator.Mode.EnglishToFrench;
GoogleTranslator.Mode reverseMode = GoogleTranslator.Mode.FrenchToEnglish;
GoogleTranslator.Mode mode = GoogleTranslator.Mode.EnglishToFrench;
GoogleTranslator.Mode reverseMode = GoogleTranslator.Mode.FrenchToEnglish;
if (radioGerman.Checked)
{
mode = GoogleTranslator.Mode.EnglishToGerman;
reverseMode = GoogleTranslator.Mode.GermanToEnglish;
}
else
{
if (radioItalian.Checked)
{
mode = GoogleTranslator.Mode.EnglishToItalian;
reverseMode = GoogleTranslator.Mode.ItalianToEnglish;
}
else
{
if (radioSpanish.Checked)
{
mode = GoogleTranslator.Mode.EnglishToSpanish;
reverseMode = GoogleTranslator.Mode.SpanishToEnglish;
}
else
{
if (radioPortugese.Checked)
{
mode = GoogleTranslator.Mode.EnglishToPortugese;
reverseMode = GoogleTranslator.Mode.PortugeseToEnglish;
}
else
{
if (radioChina.Checked)
{
mode = GoogleTranslator.Mode.EnglishToChina;
reverseMode = GoogleTranslator.Mode.ChinaToEnlish;
}
}
}
}
}
{
mode = GoogleTranslator.Mode.EnglishToGerman;
reverseMode = GoogleTranslator.Mode.GermanToEnglish;
}
else
{
if (radioItalian.Checked)
{
mode = GoogleTranslator.Mode.EnglishToItalian;
reverseMode = GoogleTranslator.Mode.ItalianToEnglish;
}
else
{
if (radioSpanish.Checked)
{
mode = GoogleTranslator.Mode.EnglishToSpanish;
reverseMode = GoogleTranslator.Mode.SpanishToEnglish;
}
else
{
if (radioPortugese.Checked)
{
mode = GoogleTranslator.Mode.EnglishToPortugese;
reverseMode = GoogleTranslator.Mode.PortugeseToEnglish;
}
else
{
if (radioChina.Checked)
{
mode = GoogleTranslator.Mode.EnglishToChina;
reverseMode = GoogleTranslator.Mode.ChinaToEnlish;
}
}
}
}
}
// Translate the text and update the display
lblStatus.Text = "Translating...";
lblStatus.Update();
GoogleTranslator gt = new GoogleTranslator(mode);
string strTranslation = gt.translate(strEnglish);
editTranslation.Text = strTranslation;
editTranslation.Update();
lblStatus.Text = "Translating...";
lblStatus.Update();
GoogleTranslator gt = new GoogleTranslator(mode);
string strTranslation = gt.translate(strEnglish);
editTranslation.Text = strTranslation;
editTranslation.Update();
lblStatus.Text = "Reverse translating...";
lblStatus.Update();
gt = new GoogleTranslator(reverseMode);
string strReverseTranslation = gt.translate(strTranslation);
editReverseTranslation.Text = strReverseTranslation;
lblStatus.Text = "";
}
详细的我就不说了,自己开源码吧。
lblStatus.Update();
gt = new GoogleTranslator(reverseMode);
string strReverseTranslation = gt.translate(strTranslation);
editReverseTranslation.Text = strReverseTranslation;
lblStatus.Text = "";
}
详细的我就不说了,自己开源码吧。
GoogleTranslator.src.rar (96.09 kb)