0

I am using SendKeys.SendWait to send keyboard keys to active window and in case the keyboard language is non English I want to change the keyboard language:

     var currentInputLang = InputLanguage.CurrentInputLanguage;
     var culture = currentInputLang.Culture.Name;
     
     var lang = InputLanguage.InstalledInputLanguages.OfType<InputLanguage>().Where(l
 => l.Culture.Name.StartsWith("en-US")).FirstOrDefault();
     if (lang != null)
         InputLanguage.CurrentInputLanguage = lang;

So this command works only if my WPF application is with focus, Any ideas how to change this keyboard language any way ?

UPDATE

XAML: This is how I start my view model class:

<Window.DataContext>
        <viewmodel:ViewModelBase/>
</Window.DataContext>

public class ViewModelBase : INotifyPropertyChanged
{
  public ViewModelBase()
  {
       MyCommand = new MyCommand(this);
  }  
}

My send keys command:

public class SaveCommand : ICommand
    {
        public ViewModelBase ViewModel { get; set; }

        public SaveCommand(ViewModelBase viewModel)
        {
            ViewModel = viewModel;
        }

        public void Execute(object parameter)
        }
            ChangeKeyboardToEnglish();
            
            // Send keys
            Thread.Sleep(500);
            SendKeys.SendWait(user);
            Thread.Sleep(150);
            SendKeys.SendWait("{TAB}");
            Thread.Sleep(150);
            SendKeys.SendWait(password);
            Thread.Sleep(150);
            SendKeys.SendWait("{ENTER}");
        }

        private void ChangeKeyboardToEnglish()
        {
            var currentInputLang = InputLanguage.CurrentInputLanguage;
            var culture = currentInputLang.Culture.Name;

            var lang = InputLanguage.InstalledInputLanguages.OfType<InputLanguage>().Where(l => l.Culture.Name.StartsWith("en-US")).FirstOrDefault();
            if (lang != null)
                InputLanguage.CurrentInputLanguage = lang;
            Thread.Sleep(250);
        }
    }
user1860934
  • 417
  • 2
  • 9
  • 22
  • Show the code that reaches this code, how do you get here? – o_w Dec 16 '20 at 08:50
  • Please see my update – user1860934 Dec 19 '20 at 16:29
  • How does the user execute this command if the window is not active? Also, when the window is active, you do not verify that your controls are focused. Changing the culture globally can be done on the thread: https://stackoverflow.com/questions/7454024/setting-culture-en-in-globally-in-wpf-application – o_w Dec 21 '20 at 11:30

0 Answers0