How does sendInput() function work in C#?

时间:2015-06-15 14:34:08

标签: c#

I'm doing a project using key stimulation and I'm using two ways to display a key character on the screen. First I use Clipboard but using Clipboard sometimes is inconvenient so I try to use SendInput() to display the key character when user press any button on the keyboard. I follow the code tutorial but I didn't know how does the SendInput() function work ( I mean when I invoke SendInput() what will it work step by step?). Does anyone have experience about my case? Please explain clearly for me. Thanks all!

private void SendUnicode(string _text)
    {
        if (IntPtr.Size == 4)
        {
            ViKey.INPUT[] input = new ViKey.INPUT[_text.Length * 2];
            for (int i = 0; i < _text.Length; i++)
            {
                input[i * 2].type = 1;
                input[i * 2].ki.wVk = 0;
                input[i * 2].ki.wScan = (short)_text[i];
                input[i * 2].ki.dwFlags = 4;
                input[i * 2 + 1] = input[i * 2];
                input[i * 2 + 1].ki.dwFlags = 6;
            }
            ViKey.SendInput((uint)input.Length, input, Marshal.SizeOf(input[0]));
            return;
        }
        else
        {
            ViKey.INPUT64[] inputx64 = new ViKey.INPUT64[_text.Length * 2];
            for (int i = 0; i < _text.Length; i++)
            {
                inputx64[i * 2].type = 1;
                inputx64[i * 2].ki.wVk = 0;
                inputx64[i * 2].ki.wScan = (short)_text[i];
                inputx64[i * 2].ki.dwFlags = 4;
                inputx64[i * 2 + 1] = inputx64[i * 2];
                inputx64[i * 2 + 1].ki.dwFlags = 6;
            }
            ViKey.SendInput((uint)inputx64.Length, inputx64, Marshal.SizeOf(inputx64[0]));
        }
    }

1 个答案:

答案 0 :(得分:0)

All relevant information can be found in the documentation about the function.

The function returns the number of events that it successfully inserted into the keyboard or mouse input stream. If the function returns zero, the input was already blocked by another thread.

So how it works is that it inserts the events in the INPUT structures (which are fed to the function through the parameters) serially into the keyboard or mouse input stream and then returns the number of those events that are successfully inserted..