Introduction
With the help of Microsoft Translator API with Spy++ logic, you can just drag the
Spy++ finder control on the control's label whose text you want to translate. Use translate functionality and view the change immediately. This is helpful while you are coding in one language and want to test the label text at runtime in some other language
Background
Here Microsoft Translator API is used which is free if usage is very low. The user has to obtain his own Id and secret key from Microsoft as per his needs. Below is the link where you will get these things. Don't worry you will get it free of cost (remember to choose free subscription):
http://msdn.microsoft.com/en-us/library/hh454950.aspx
Using the code
For capturing current window handle from Mouse Pointer location, below code is used:
IntPtr hWnd = Win32.WindowFromPoint(Cursor.Position);
From the selected control, control text is extracted which will be our text input to translate.
As mentioned above, obtain your Id and Secret Key from Microsoft and add it in App config file.
="1.0"
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
<appSettings>
<add key="MicrosoftTranslatorClientID" value="" />
<add key="MicrosoftTranslatorSecretID" value="" />
</appSettings>
</configuration>
Choose languages to translate to and translate from and click on Translate.
Below is the main function which translates the text:
private static string Translate(string authToken,
string strTextToConvert, string strLanFrom, string strLangTo)
{
string languageDetected = string.Empty;
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" +
strTextToConvert + "&from=" + strLanFrom + "&to=" + strLangTo;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers.Add("Authorization", authToken);
WebResponse response = null;
try
{
response = httpWebRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
System.Runtime.Serialization.DataContractSerializer dcs =
new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
languageDetected = (string)dcs.ReadObject(stream);
}
}
catch
{
throw;
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
}
return languageDetected;
}
Now just click on view the change and your translated text will be appeared on control at runtime:
[DllImport("user32.dll")]
static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int msg, int Param, string s);
private void SetTextt(IntPtr hWnd, string text)
{
hWnd=(IntPtr)Int32.Parse(_textBoxHandle.Text);
SendMessage(hWnd, WM_SETTEXT, 0, text);
WindowHighlighter.Refresh(hWnd);
}