/* PressKeys(Win32API.VKCodes[] vkCodes) * press combine keys, like alt+F4. */ public unsafe static void PressKeys(Win32API.VKCodes[] vkCodes) { if (vkCodes == null || vkCodes.Length == 0) { return; } int len = vkCodes.Length; Win32API.INPUT *structInput = stackalloc Win32API.INPUT[len * 2]; structInput[0].type = structInput[1].type = 1; //keyboard structInput[0].ki.time = structInput[1].ki.time = 0; structInput[0].ki.dwFlags = structInput[1].ki.dwFlags = 4; //unicode for (int i = 0; i < len; i++) { structInput[i].ki.wVk = structInput[len * 2 - i - 1].ki.wVk = (ushort)vkCodes[i]; //key up structInput[len * 2 - i - 1].ki.dwFlags = 2; } //send the key Win32API.SendInput((uint)(len * 2), structInput, Marshal.SizeOf(*structInput)); }
/* void PressKey(Win32API.VKCodes vkCode) * Press a single key. */ public unsafe static void PressKey(Win32API.VKCodes vkCode) { Win32API.INPUT *structInput = stackalloc Win32API.INPUT[2]; structInput[0].type = structInput[1].type = 1; //keyboard structInput[0].ki.wVk = structInput[1].ki.wVk = (ushort)vkCode; structInput[0].ki.time = structInput[1].ki.time = 0; structInput[0].ki.dwFlags = structInput[1].ki.dwFlags = 4; //unicode //key up structInput[1].ki.dwFlags = 2; //send the key Win32API.SendInput(2, structInput, Marshal.SizeOf(*structInput)); }
/* void SendChars(string str) * send normal characters to system. * except special keys like tab, ctrl etc. * NOTICE: why not use SendWait directly? * because I found sometimes SendWait can NOT send the character correctly. */ public unsafe static void SendChars(string str) { if (String.IsNullOrEmpty(str)) { return; } //struct for keyboard event. Win32API.INPUT *structInput = stackalloc Win32API.INPUT[2]; structInput[0].type = structInput[1].type = 1; //keyboard structInput[0].ki.wVk = structInput[1].ki.wVk = 0; structInput[0].ki.time = structInput[1].ki.time = 0; structInput[0].ki.dwFlags = structInput[1].ki.dwFlags = 4; //unicode for (int i = 0; i < str.Length; i++) { //key down structInput[0].ki.wScan = structInput[1].ki.wScan = str[i]; //key up structInput[1].ki.dwFlags = 2; //send the character Win32API.SendInput(2, structInput, Marshal.SizeOf(*structInput)); } }