博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#: Get current keyboard layout\input language
阅读量:6079 次
发布时间:2019-06-20

本文共 2047 字,大约阅读时间需要 6 分钟。

原文 

  On some occasions, you may want to get a "global" input language - that is, the keyboard layout used by the current foreground window\application\whatever. Basically, simulating the behaviour of the language panel on Windows.

The common use cases are on-screen keyboards, fullscreen applications, and widgets.

While I wasn't able to find a premade function that get this particular thing during my searches, it turned out not to be too hard to assemble:

[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.    }}

 

So, first, we import a couple of functions from user32.dll:

  • GetForegroundWindow, to get the current foreground\active window' pointer.
  • GetWindowThreadProcessId, to get the ID of the thread that created the particular window.
  • GetKeyboardLayout, to get the keyboard layout ID currently used by the given thread.

The actual function then proceeds to combine these in a straightforward manner to obtain the keyboard layout ID for the current active window.

Then a System.Globalization.CultureInfo is created based on ID, permitting to conveniently get the language name in various formats and a handful of other useful information.

If there's no foreground window available, GetKeyboardLayout will return 0 (which is not a valid ID for CultureInfo), and the catch-block will return En-US as a fallback language (alternatively, you can return null and handle that separately).

And that's it. Have fun!

转载地址:http://ijhgx.baihongyu.com/

你可能感兴趣的文章
javascript中的链表结构—从链表中删除元素
查看>>
用实例揭示notify()和notifyAll()的本质区别
查看>>
Android MediaPlayer接口及状态迁移
查看>>
JQuery------prevAll(),nextAll(),attr()方法的使用
查看>>
Disciz!NT开源资源汇总
查看>>
Python网络编程笔记
查看>>
Vim自动补全神器–YouCompleteMe
查看>>
Mysql 小工具
查看>>
个人andriod实习小作品,个人联网笔记本
查看>>
Codeforces Round #313 (Div. 2) 解题报告
查看>>
go7---map
查看>>
CentOS5.4安装redmine详细步骤
查看>>
runloop的source
查看>>
eclipse A Java Runtime Environment(JRE)
查看>>
Sqlserver建立Oracle的鏈接服務器
查看>>
根据IP获取所在的国家城市
查看>>
python Selenium+phantomjs 小技巧
查看>>
linux每日命令(1):ls命令
查看>>
ArrayBlockingQueue源码解析(2)
查看>>
哈希表
查看>>