-
-
Save dzonesasaki/6cd6facaa77a420250b74704ddf8c311 to your computer and use it in GitHub Desktop.
C#でSendInputを使う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Runtime.InteropServices; | |
namespace SendKey | |
{ | |
class SendKey | |
{ | |
// ref to https://gist.github.com/romichi/4971512 | |
[StructLayout(LayoutKind.Sequential)] | |
private struct MOUSEINPUT | |
{ | |
public int dx; | |
public int dy; | |
public int mouseData; | |
public int dwFlags; | |
public int time; | |
public int dwExtraInfo; | |
}; | |
[StructLayout(LayoutKind.Sequential)] | |
private struct KEYBDINPUT | |
{ | |
public short wVk; | |
public short wScan; | |
public int dwFlags; | |
public int time; | |
public int dwExtraInfo; | |
}; | |
[StructLayout(LayoutKind.Sequential)] | |
private struct HARDWAREINPUT | |
{ | |
public int uMsg; | |
public short wParamL; | |
public short wParamH; | |
}; | |
[StructLayout(LayoutKind.Explicit)] | |
private struct INPUT | |
{ | |
[FieldOffset(0)] | |
public int type; | |
[FieldOffset(4)] | |
public MOUSEINPUT no; | |
[FieldOffset(4)] | |
public KEYBDINPUT ki; | |
[FieldOffset(4)] | |
public HARDWAREINPUT hi; | |
}; | |
[DllImport("user32.dll")] | |
private extern static void SendInput(int nInputs, ref INPUT pInputs, int cbsize); | |
[DllImport("user32.dll", EntryPoint = "MapVirtualKeyA")] | |
private extern static int MapVirtualKey(int wCode, int wMapType); | |
private const int INPUT_KEYBOARD = 1; | |
private const int KEYEVENTF_KEYDOWN = 0x0; | |
private const int KEYEVENTF_KEYUP = 0x2; | |
private const int KEYEVENTF_EXTENDEDKEY = 0x1; | |
// ref to https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes | |
private const int VK_LEFT = 0x25; | |
private const int VK_Z = 0x5A; | |
public void Send(int key, bool isEXTEND) | |
{ | |
/* | |
* Keyを送る | |
* 入力 | |
* isEXTEND : 拡張キーかどうか | |
*/ | |
INPUT inp = new INPUT(); | |
// 押す | |
inp.type = INPUT_KEYBOARD; | |
inp.ki.wVk = (short)key; | |
inp.ki.wScan = (short)MapVirtualKey(inp.ki.wVk, 0); | |
inp.ki.dwFlags = ((isEXTEND) ? (KEYEVENTF_EXTENDEDKEY) : 0x0) | KEYEVENTF_KEYDOWN; | |
inp.ki.time = 0; | |
inp.ki.dwExtraInfo = 0; | |
SendInput(1, ref inp, Marshal.SizeOf(inp)); | |
System.Threading.Thread.Sleep(100); | |
// 離す | |
inp.ki.dwFlags = ((isEXTEND) ? (KEYEVENTF_EXTENDEDKEY) : 0x0) | KEYEVENTF_KEYUP; | |
SendInput(1, ref inp, Marshal.SizeOf(inp)); | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
System.Threading.Thread.Sleep(2000); | |
SendKey s = new SendKey(); | |
const int VK_LEFT = 0x25; | |
const int VK_Z = 0x5A; | |
s.Send(VK_Z, false); | |
s.Send(VK_LEFT, true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment