備忘録

備忘録

C#でマウスとキーボードを操作する方法

Ⅰ. はじめに

タイトルの通り「C#でマウスとキーボードを操作する方法」です。

Ⅱ. 手順

1. 必要なパッケージをインストールする
dotnet add package InputSimulatorPlus --version 1.0.7
2. サンプルプログラムを書く
using WindowsInput;
using WindowsInput.Native;

double GetAbsoluteX(int x) => x * 65535 / Screen.PrimaryScreen.Bounds.Width;
double GetAbsoluteY(int y) => y * 65535 / Screen.PrimaryScreen.Bounds.Height;

var inputSimulator = new InputSimulator();
inputSimulator.Keyboard.KeyPress(VirtualKeyCode.VK_A);
inputSimulator.Mouse.LeftButtonClick();
inputSimulator.Mouse.MoveMouseTo(GetAbsoluteX(100), GetAbsoluteY(100));

実行結果

省略