Skip to content

Instantly share code, notes, and snippets.

@dzonesasaki
Forked from romichi/SendKey.cs
Last active March 2, 2021 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dzonesasaki/6cd6facaa77a420250b74704ddf8c311 to your computer and use it in GitHub Desktop.
Save dzonesasaki/6cd6facaa77a420250b74704ddf8c311 to your computer and use it in GitHub Desktop.
C#でSendInputを使う
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