Delphi: Learn how to detect language changes while run time?

Detect language changes while run time.



Source code

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm2 = class(TForm)
    Edit1: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    Button1: TButton;
    Label1: TLabel;
    Edit4: TEdit;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure OnChangeLanguageEvent(var Msg: TMessage);
      message CM_INPUTLANGCHANGE;
    function ShowKeyboardLayoutName(const localeStr: string): string;

  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

function TForm2.ShowKeyboardLayoutName(const localeStr: string): string;
Var
  LayoutName: Array [0 .. KL_NAMELENGTH] of Char;
  LangName: Array [0 .. 63] of Char;
begin
  if localeStr = '' then
  begin
    GetKeyboardLayoutName(@LayoutName[0]);
    GetLocaleInfo(StrToInt('$' + string(LayoutName)), LOCALE_SENGLANGUAGE,
      @LangName, 64);
  end
  else
  begin
    GetKeyboardLayoutName(@LayoutName[0]);
    GetLocaleInfo(StrToInt('$' + localeStr), LOCALE_SENGLANGUAGE,
      @LangName, 64);
  end;

  result := LangName;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  Label1.Caption := UpperCase(ShowKeyboardLayoutName(''));
end;

procedure TForm2.OnChangeLanguageEvent(var Msg: TMessage);
var
  szBuf: array [0 .. KL_NAMELENGTH] of Char;
begin
  Screen.ActiveControl.Perform(WM_KILLFOCUS, 0, 0);
  Screen.ActiveControl.Perform(WM_SETFOCUS, 0, 0);

  GetKeyboardLayoutName(@(szBuf[0]));
  Label1.Caption := UpperCase(ShowKeyboardLayoutName(string(szBuf)));
  inherited;
end;

end.

Comments