public MainForm() { InitializeComponent(); ListenerThread = new Thread(() => { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(new IPEndPoint(IPAddress.Any, Settings.Default.ListeningPort)); var oldbuttons = new BitField(8); var oldkeystate = new BitField(256); var recvbuffer = new byte[40]; var rawmousepacket = new byte[Marshal.SizeOf <MouseStatePacketType>()]; var rawkeyboardpacket = new byte[Marshal.SizeOf <KeyboardStatePacketType>()]; while (true) { socket.Receive(recvbuffer); switch (recvbuffer[0]) { case 1: { // mouse Array.Copy(recvbuffer, rawmousepacket, rawmousepacket.Length); var packetwrapper = new MouseStatePacketWrapperType(rawmousepacket.ToObject <MouseStatePacketType>()); InputSimulator.ApplyPacket(packetwrapper, oldbuttons); oldbuttons.CopyFrom(packetwrapper.Buttons); } break; case 2: { // keyboard Array.Copy(recvbuffer, rawkeyboardpacket, rawkeyboardpacket.Length); var packetwrapper = new KeyboardStatePacketWrapperType(rawkeyboardpacket.ToObject <KeyboardStatePacketType>()); InputSimulator.ApplyPacket(packetwrapper, oldkeystate); oldkeystate.CopyFrom(packetwrapper.KeyState); } break; default: continue; } } }) { Name = "Listener Thread", IsBackground = true }; ListenerThread.Start(); }
public static void ApplyPacket(KeyboardStatePacketWrapperType packetwrapper, BitField oldkeystate) { var inputs = new List <Input>(); for (var vk = 0; vk < packetwrapper.KeyState.DataLength; ++vk) { var oldstate = oldkeystate[vk]; var newstate = packetwrapper.KeyState[vk]; if (oldstate != newstate) { var input = new Input { type = SendInputEventType.InputKeyboard }; input.mkhi.ki.wVk = (ushort)vk; input.mkhi.ki.dwFlags = newstate && !oldstate ? 0 : KeyboardEventFlags.KEYUP; inputs.Add(input); } } SendInput((uint)inputs.Count, inputs.ToArray(), Marshal.SizeOf <Input>()); }