本文告诉大家如何获得 WPF 输入法的语言区域
需要使用 user32 的方法,很简单,请看下面
代码语言:javascript复制 [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 请看下面
代码语言:javascript复制 <Grid>
<TextBlock x:Name="CeareamearTreseretal" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
</Grid>
这样可以在后台代码给一个值
代码语言:javascript复制 private async void HairjurNalllairmo()
{
while (true)
{
await Task.Delay(100);
CeareamearTreseretal.Text = GetCurrentKeyboardLayout().DisplayName;
}
}
这时修改语言区域就可以看到变化
参见 C#: Get current keyboard layoutinput language