[C#][API]SendInput

  • 10954
  • 0
  • C#
  • 2011-06-28

摘要:[C#][API]SendInput

宣告:

 

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern uint SendInput(uint nInput, ref INPUT pInput, int cbSize);


        [StructLayout(LayoutKind.Explicit)]
        internal struct INPUT
        {
            [FieldOffset(0)]
            internal int type;//0:mouse event;1:keyboard event;2:hardware event
            [FieldOffset(4)]
            internal MOUSEINPUT mi;
            [FieldOffset(4)]
            internal KEYBDINPUT ki;
            [FieldOffset(4)]
            internal HARDWAREINPUT hi;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct HARDWAREINPUT
        {
            internal int uMsg;
            internal short wParamL;
            internal short wParamH;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct KEYBDINPUT
        {
            internal ushort wVk;
            internal ushort wScan;
            internal uint dwFlags;
            internal uint time;
            internal IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MOUSEINPUT
        {
            internal int dx;
            internal int dy;
            internal int mouseData;
            internal int dwFlags;
            internal int time;
            internal IntPtr dwExtraInfo;
        }

使用:
 

            //按住Caps Lock
            INPUT Input=new INPUT();
            Input.type = 1; //keyboard_input
            Input.ki.wVk = 0x14; //CAPS_Lock
            Input.ki.dwFlags = 0;
            SendInput(1, ref Input, Marshal.SizeOf(Input));
             
            //放開Caps Lock
            Input = new INPUT();
            Input.type = 1;
            Input.ki.wVk = 0x14;
            Input.ki.dwFlags = 2;//key_up
            SendInput(1, ref Input, Marshal.SizeOf(Input));   

 

要注意的是 雖然在MSDN 中SendInput的第二個參數 寫到 : An array of Input structures.
但實測後,並不能使用陣列的方式,否則會失敗並且得到參數錯誤(0x57)。

參考 SendInput