pinvoke函数getKeyBoardLayout()的错误

我正在尝试编写一个基本的背景键盘记录器...键盘scanCodes和States通过pinvoke函数ToAsciiEx或ToUnicodeEx进行转换。这些函数有一个KeyboardLayout参数。我有一个功能(见下文)获取当前(活动窗口)键盘布局。但此函数始终返回0.错误代码为6(ERROR_INVALID_HANDLE)。 任何sugessions? thx的答案
    static public IntPtr getActiveKeyBoardLayout() 
    {             
        int handle = 0;
        handle = GetForegroundWindow();

        IntPtr i = new IntPtr(handle);
        HandleRef hr = new HandleRef(wrapper, i);
        int pid;
        GetWindowThreadProcessId(hr, out pid);

        IntPtr layout = GetKeyboardLayout(pid);

        int er = Marshal.GetLastWin32Error();
        if (er > 0)
        {
            System.Console.Out.WriteLine("error " + er.ToString());
        }

        return layout;
    }
    
已邀请:
您正在将进程ID传递给该函数。它需要一个线程ID。 GetWindowThreadProcessId()的返回值。使用Marshal.GetLastWin32Error()的方式也是错误的,只应在API函数返回失败代码时使用它。     

要回复问题请先登录注册