本文告诉大家如何获得 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/post/WPF-%E8%8E%B7%E5%BE%97%E5%BD%93%E5%89%8D%E8%BE%93%E5%85%A5%E6%B3%95%E8%AF%AD%E8%A8%80%E5%8C%BA%E5%9F%9F.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者前往 CSDN 关注我的主页

知识共享许可协议 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号

欢迎进入 Eleven 老师组建的 .NET 社区

以上广告全是友情推广,无盈利