たるきちのあれこれ









  Topプログラミングサンプル ▶ キーストロークをウインドウに送信

キーストロークをアクティブウインドウに送信するサンプルです。

C#

// アクティブウインドウに「AbCあ」を送信
SendKeys.SendWait("AbCあ");

キーコード表
 A  "A" 
 AAAAA  "{A 5}" 
 ABC  "ABC" 
 [SHIFT] A  "+A" 
 [CTRL] A  "^A" 
 [ALT] A  "%A" 
 [F1]  "{F1}" 
 [BACKSPACE]  "{BS}" 
 [BREAK]  "{BREAK}" 
 [CAPSLOCK]  "{CAPSLOCK}" 
 [DEL]  "{DEL}" 
 [END]  "{END}" 
 [ENTER]  "{ENTER}" 
 [ESC]  "{ESC}" 
 [HOME]  "{HOME}" 
 [INS]  "{INS}" 
 [NUMLOCK]  "{NUMLOCK}" 
 [PageDown]  "{PGDN}" 
 [PageUp]  "{PGUP}" 
 [PRTSC]  "{PRTSC}" 
 [TAB]  "{TAB}" 
 [↑]  "{UP}" 
 [↓]  "{DOWN}" 
 [←]  "{LEFT}" 
 [→]  "{RIGHT}" 
 +  "{+}" 
 ^  "{^}" 
 %  "{%}" 
 ~  "{~}" 
 (  "{(}" 
 )  "{)}" 
 {  "{{}" 
 }  "{}}" 
 [  "{[}" 
 ]  "{]}" 


キーストロークを非アクティブウインドウに送信するサンプルです。

C#

// using System.Runtime.InteropServices;

[DllImport("user32.dll")]
private static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImport("user32.dll")]
private static extern int VkKeyScan(char ch);

// デスクトップのウインドウハンドル取得
IntPtr hwnd = GetDesktopWindow();
// メモ帳のウインドウハンドル取得
hwnd = FindWindowEx(hwnd, IntPtr.Zero, "notepad", null);
// メモ帳ウインドウ内の「edit」ウインドウのハンドル取得
hwnd = FindWindowEx(hwnd, IntPtr.Zero, "edit", null);

// 「edit」ウインドウに「aab」を送信
PostMessage(hwnd, 0x0100, VkKeyScan('a'), 0);
PostMessage(hwnd, 0x0100, 0x41, 0);
PostMessage(hwnd, 0x0100, 0x42, 0);

キーコード表
 BACKSPACE  0x08 
 TAB  0x09 
 ENTER  0x0D 
 SHIFT  0x10 
 CTRL  0x11 
 ALT  0x12 
 PAUSE  0x13 
 CAPSLOCK  0x14 
 ESC  0x1B 
 SPACE  0x20 
 PGUP  0x21 
 PGDN  0x22 
 END  0x23 
 HOME  0x24 
 ←  0x25 
 ↑  0x26 
 →  0x27 
 ↓  0x28 
 PRTSC  0x2C 
 INS  0x2D 
 DEL  0x2E 
 0 〜 9  0x30 〜 0x39 
 A 〜 Z  0x41 〜 0x5A 
 F1 〜 F24  0x70 〜 0x87