0

I want to know when the Layout(keyboard layout) for the current input language changes on Windows OS. I've tried to work with this -

InputLanguageManager.Current.InputLanguageChanged += Current_InputLanguageChanged;

But this event doesn't come up if I'm changing from Portuguese (Brazil) Portuguese (Brazil ABNT) ----> Portuguese (Brazil) United States-International

Another example is when I change from English (United States) US ----> English (United States) German

niks_4143
  • 87
  • 1
  • 7
  • have you read http://stackoverflow.com/questions/10299659/is-it-possible-to-detect-keyboard-focus-events-globally ?? – BugFinder Mar 03 '17 at 07:35
  • Can you tell us the steps of manually change the current input language? – Lei Yang Mar 03 '17 at 07:38
  • I'm using Windows 10 OS and I've added keyboard layout from : *Language Preferences -> Chose one of the language -> Click Options -> Add Keyboard*. Now In your language options when you switch between two layout names(eg:- Portuguese (Brazil ABNT) and United States-International) then the event *InputLanguageChanged* is not raised. – niks_4143 Mar 03 '17 at 07:45

1 Answers1

0

Based on this and this, you can use the following code:

public partial class MainWindow : Window
{ 
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern IntPtr GetKeyboardLayout(uint idThread);
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr processId);

    public MainWindow()
    {  
        InitializeComponent();

        Task.Factory.StartNew(() =>
        {
            while (true)
            {
                HandleCurrentLanguage();
                System.Threading.Thread.Sleep(500);
            }
        }); 
    }


    IntPtr _currentKeyboardLayout = IntPtr.Zero;
    private void HandleCurrentLanguage()
    {
        var newLayout = GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero));
        if (_currentKeyboardLayout != newLayout)
        {
            _currentKeyboardLayout = newLayout;
            // do something 
        }
    }  
}

Please note that the converting the result of GetKeyboardLayout to CultureInfo as suggested in the second link I provided, did not worked for me.

Community
  • 1
  • 1
rmojab63
  • 3,513
  • 1
  • 15
  • 28
  • note that instead of Task.Factory.StartNew you can check the condition in keydown and mousedoen events. – rmojab63 Mar 04 '17 at 13:11