SendInput and 64bits

前端 未结 2 1375
长发绾君心
长发绾君心 2020-11-27 21:17

Below is an extract of some code I am using to simulate key presses via the SendInput API. This works correctly if I set my application to compile for an x86 CPU, but doesn\

相关标签:
2条回答
  • 2020-11-27 21:43

    dwExtraInfo is a pointer.
    Therefore, it needs to be 4 bytes wide in 32-bit code and 8 bytes in 64-bit code.

    To do that in C#, use IntPtr (not uint, which is always 4 bytes)

    0 讨论(0)
  • 2020-11-27 21:59

    Further to the error that SLaks identified, your remaining problem is that the size of INPUT is incorrect. This means that SendInput fails since it receives a parameter of type INPUT[]. You can't specify the size with StructLayout(LayoutKind.Explicit, Size = 28) since you want code that handles both x86 and x64.

    This all stems from the fact that you have only included the the KEYBRDINPUT struct in INPUT. The MOUSEINPUT struct is larger than KEYBRDINPUT which is the cause of your problem.

    The best solution is to define the INPUT structure correctly, including the union part. Do this like so (declarations taken from pinvoke.net).

    [StructLayout(LayoutKind.Sequential)]
    struct MOUSEINPUT
    {
        public int dx;
        public int dy;
        public uint mouseData;
        public uint dwFlags;
        public uint time;
        public IntPtr dwExtraInfo;
    }
    
    [StructLayout(LayoutKind.Sequential)]
    struct KEYBDINPUT 
    {
         public ushort wVk;
         public ushort wScan;
         public uint dwFlags;
         public uint time;
         public IntPtr dwExtraInfo;
    }
    
    [StructLayout(LayoutKind.Sequential)]
    struct HARDWAREINPUT
    {
         public int uMsg;
         public short wParamL;
         public short wParamH;
    }
    
    [StructLayout(LayoutKind.Explicit)]
    struct MouseKeybdHardwareInputUnion
    {
        [FieldOffset(0)]
        public MOUSEINPUT mi;
    
        [FieldOffset(0)]
        public KEYBDINPUT ki;
    
        [FieldOffset(0)]
        public HARDWAREINPUT hi;
    }
    
    [StructLayout(LayoutKind.Sequential)]
    struct INPUT
    {
        public uint type;
        public MouseKeybdHardwareInputUnion mkhi;
    }
    
    0 讨论(0)
提交回复
热议问题