使用WindowsAPICodePack实现翻译功能

仅限于以下几种语言间的翻译:

                       

 

 

 

在我的另一篇博文《图片批量压缩》中,有介绍WindowsAPICodePack库,该库是微软提供的一套基于Win7及以上版本操作系统的系统库,可以帮助我们完成一些代码很难完成的系统层面操作。本文就介绍其中的一个强大功能:语言的翻译转换功能。WindowsAPICodePack库下载地址:官方主页

 

程序界面如下:

 

 

获取所有翻译类别代码:

//获取所有翻译类别
        private MappingService[] GetSpecifiedMappingServices(string CategoryName)
        {
            MappingService[] transliterationServices = null;
            try
            {
                MappingEnumOptions enumOptions = new MappingEnumOptions() { Category = CategoryName };
                transliterationServices = MappingService.GetServices(enumOptions);
            }
            catch (LinguisticException exc)
            {
                MessageBox.Show(exc.Message);
            }
            return transliterationServices;
        }

  

解释:前面贴出的可以翻译的几种语言,是系统给出的,并不是博主创造的,上面的代码就是从系统中获取所有支持的语言翻译功能。

 

翻译功能代码如下:

private string LanguageConverter(Guid serviceGuid, string sourceContent)
        {
            string transliterated = null;
            if ((sourceContent != null) && (sourceContent.Length > 0))
            {
                try
                {
                    MappingService mapService = new MappingService(serviceGuid);
                    using (MappingPropertyBag bag = mapService.RecognizeText(sourceContent, null))
                    {
                        transliterated = bag.GetResultRanges()[0].FormatData(new StringFormatter());
                    }
                }
                catch (LinguisticException exc)
                {
                    MessageBox.Show(exc.Message);
                }
            }
            return transliterated;
        }

  

解释:通过serviceGuid初始化不同的翻译器,serviceGuid就是下拉列表中选择的语言的guid。

 

调用翻译功能的代码:

try
            {
                guidService = ((DataItem)comboBox1.SelectedItem).guid;
                string result = LanguageConverter(guidService.GetValueOrDefault(), txtSource.Text);
                if ((result != null) && (result.Length > 0))
                {
                    txtResult.Text = result;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

  

解释:略。

 

下载:Demo   Code

posted @ 2014-05-06 23:03  小y  阅读(2452)  评论(0编辑  收藏  举报