如何使用模态 window 将 WM_INPUTLANGCHANGEREQUEST 发送到应用程序?

How to send WM_INPUTLANGCHANGEREQUEST to app with modal window?

我写了一个键盘切换器,效果很好,但如果当前应用程序打开了模态window,它就会失败。在键盘开关上,我执行以下操作

hwnd = GetForegroundWindow();
PostMessage(hwnd, WM_INPUTLANGCHANGEREQUEST, IntPtr.Zero, handle);

哪里

[DllImport("User32.dll", EntryPoint = "PostMessage")]
private static extern int PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

但语言没有改变。

我该如何完成?


添加 get root owner 改善了情况,但没有完全帮助。

添加对 GetDesktopWindow 的调用没有帮助:

hwnd = GetDesktopWindow();
InputLangChangeRequest(hwnd, language);
hwnd = GetRootOwner();
InputLangChangeRequest(hwnd, language);

代码在这里https://github.com/dims12/NormalKeyboardSwitcher

使用GetAncestor

Retrieves the owned root window by walking the chain of parent and owner windows returned by GetParent.

这应该return主要UIwindow如果有模态window,或者模态链window.

hwnd = GetForegroundWindow();
hwnd = GetAncestor(hwnd, GA_ROOTOWNER); //#define GA_ROOTOWNER 3


如果目标本身是基于对话框的应用程序,显然 WM_INPUTLANGCHANGEREQUEST 会失败(我不知道为什么!)要解决这个问题,您可以 post WM_INPUTLANGCHANGEREQUEST 向对话框的后代发送消息(除了 WM_INPUTLANGCHANGEREQUEST 消息到对话框本身)

static bool MyEnumProc(IntPtr hwnd, IntPtr lParam)
{
    PostMessage(hwnd, WM_INPUTLANGCHANGEREQUEST, IntPtr.Zero, lParam);
    return true;
}

static void Foo()
{
    //Greek input for testing:
    var hkl = LoadKeyboardLayout("00000408", KLF_ACTIVATE);
    var hwnd = GetForegroundWindow();
    if (hwnd != null)
    {
        hwnd = GetAncestor(hwnd, GA_ROOTOWNER);
        PostMessage(hwnd, WM_INPUTLANGCHANGEREQUEST, IntPtr.Zero, (IntPtr)hkl);

        StringBuilder buf = new StringBuilder(100);
        GetClassName(hwnd, buf, 100);

        //if this is a dialog class then post message to all descendants 
        if (buf.ToString() == "#32770")
            EnumChildWindows(hwnd, MyEnumProc, (IntPtr)hkl);
    }
}