gpt4 book ai didi

c# - 正确检测键盘布局

转载 作者:太空狗 更新时间:2023-10-30 00:48:37 26 4
gpt4 key购买 nike

我有一个 winforms 应用程序,我需要在其中获取用户的当前键盘布局。为此,我使用了 System.Windows.Forms.InputLanguage.CurrentInputLanguage.LayoutName

只要用户将表单作为事件窗口,这就可以正常工作,一旦他关注其他内容并更改语言,前一个属性将不会返回正确的值,它将返回上次使用的语言,而表单仍然是事件窗口。

有没有一种方法我可以获得用户键盘布局的名称,即使他没有关注表单,对可以使用的内容没有限制。

最佳答案

正如您可能已经知道的那样,System.Windows.Forms.InputLanguage.CurrentInputLanguage.LayoutName 属性返回当前线程的键盘布局,无论您选择什么布局,执行线程都将保持不变,除非您选择窗口并更改该窗口的键盘输入布局。

也就是说,您实际上是想检查当前的键盘布局文化,并能够知道它何时发生变化。前一段时间我有类似的要求,我想出了以下代码,它对我很有帮助:

public delegate void KeyboardLayoutChanged(int oldCultureInfo, int newCultureInfo);

class KeyboardLayoutWatcher : IDisposable
{
private readonly Timer _timer;
private int _currentLayout = 1033;


public KeyboardLayoutChanged KeyboardLayoutChanged;

public KeyboardLayoutWatcher()
{
_timer = new Timer(new TimerCallback(CheckKeyboardLayout), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

[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 int GetCurrentKeyboardLayout()
{
try
{
IntPtr foregroundWindow = GetForegroundWindow();
uint foregroundProcess = GetWindowThreadProcessId(foregroundWindow, IntPtr.Zero);
int keyboardLayout = GetKeyboardLayout(foregroundProcess).ToInt32() & 0xFFFF;

if (keyboardLayout == 0)
{
// something has gone wrong - just assume English
keyboardLayout = 1033;
}
return keyboardLayout;
}
catch (Exception ex)
{
// if something goes wrong - just assume English
return 1033;
}
}

private void CheckKeyboardLayout(object sender)
{
var layout = GetCurrentKeyboardLayout();
if (_currentLayout != layout && KeyboardLayoutChanged != null)
{
KeyboardLayoutChanged(_currentLayout, layout);
_currentLayout = layout;
}

}

private void ReleaseUnmanagedResources()
{
_timer.Dispose();
}

public void Dispose()
{
ReleaseUnmanagedResources();
GC.SuppressFinalize(this);
}

~KeyboardLayoutWatcher()
{
ReleaseUnmanagedResources();
}
}

像这样使用它:

        new KeyboardLayoutWatcher().KeyboardLayoutChanged += (o, n) =>
{
this.CurrentLayoutLabel.Text = $"{o} -> {n}"; // old and new KB layout
};

关于c# - 正确检测键盘布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44856042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com