WPF 获得当前输入法语言区域

本文告诉大家如何获得 WPF 输入法的语言区域

需要使用 user32 的方法,很简单,请看下面

       [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hwnd, IntPtr proccess);
        [DllImport("user32.dll")] static extern IntPtr GetKeyboardLayout(uint thread);

        public CultureInfo GetCurrentKeyboardLayout()
        {
            try
            {
                IntPtr foregroundWindow = GetForegroundWindow();
                uint foregroundProcess = GetWindowThreadProcessId(foregroundWindow, IntPtr.Zero);
                int keyboardLayout = GetKeyboardLayout(foregroundProcess).ToInt32() & 0xFFFF;
                return new CultureInfo(keyboardLayout);
            }
            catch (Exception)
            {
                return new CultureInfo(1033); // Assume English if something went wrong.
            }
        }

因为没有提供语言区域变化的事件,所以需要自己写一个循环来获取

在界面添加一个 TextBlock 请看下面

    <Grid>
        <TextBlock x:Name="CeareamearTreseretal" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
    </Grid>

这样可以在后台代码给一个值

        private async void HairjurNalllairmo()
        {
            while (true)
            {
                await Task.Delay(100);
                CeareamearTreseretal.Text = GetCurrentKeyboardLayout().DisplayName;
            }
        }

这时修改语言区域就可以看到变化

参见 C#: Get current keyboard layout\input language

我搭建了自己的博客 https://blog.lindexi.com/ 欢迎大家访问,里面有很多新的博客。只有在我看到博客写成熟之后才会放在csdn或博客园,但是一旦发布了就不再更新

如果在博客看到有任何不懂的,欢迎交流,我搭建了 dotnet 职业技术学院 欢迎大家加入

[外链图片转存失败(img-srx6qYoK-1562066883557)(http://bulleimage.service.walterlv.com/api/image/csdn/article/image.png)]

[外链图片转存失败(img-09w4SwXC-1562066883557)(https://licensebuttons.net/l/by-nc-sa/4.0/88x31.png)]
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接:http://blog.csdn.net/lindexi_gd ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系

posted @ 2019-06-29 09:25  lindexi  阅读(349)  评论(0编辑  收藏  举报