質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
PyAutoGUI

PyAutoGUIは、Windows、Mac OS、Linuxに対応した、Python用のGUI自動化ライブラリです。

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

.NET Framework

.NET Framework は、Microsoft Windowsのオペレーティングシステムのために開発されたソフトウェア開発環境/実行環境です。多くのプログラミング言語をサポートしています。

DirectX

DirectX(ダイレクトエックス)は、 マイクロソフトが開発したゲーム・マルチメディア処理用のAPIの集合です。

Q&A

解決済

1回答

2318閲覧

PythonのpyautoguiやC#のSendMessageなどの仮想キー送信を使用せずにキーが押されたことをアプリに渡す方法はあるのでしょうか

deltamelon

総合スコア1

PyAutoGUI

PyAutoGUIは、Windows、Mac OS、Linuxに対応した、Python用のGUI自動化ライブラリです。

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

.NET Framework

.NET Framework は、Microsoft Windowsのオペレーティングシステムのために開発されたソフトウェア開発環境/実行環境です。多くのプログラミング言語をサポートしています。

DirectX

DirectX(ダイレクトエックス)は、 マイクロソフトが開発したゲーム・マルチメディア処理用のAPIの集合です。

0グッド

0クリップ

投稿2023/02/14 06:10

実現したいこと

  • 青鬼やゆめにっき、EveryonePianoなど他者が作成したアプリケーションをスクリプトから操作したい
  • 自身がよく使う言語、且つ、SendMessageなどに多少の知見があったためC#やPythonで試したが、全く別の言語でも可

前提

Windows11、.NET Framework4.7.2、Python3.10.7です。

上記の通り、青鬼やゆめにっき、EveryonePianoなどの他者が作成したアプリケーションをスクリプトから仮想キーを送信するなどして操作したいと思い、
C#のSendMessageやPostMessage、Pythonのpyautogui.pressやkeydownを試してみましたが、送信先のアプリが反応しませんでした。

C#のSendMessageやPostMessageで参考にした記事
https://dobon.net/vb/bbs/log3-20/12272.html
Pythonのpyautogui.pressやkeydownで参考にした記事
https://www.lisz-works.com/entry/pyautogui-key

青鬼やゆめにっきについてはキー操作のみなのでマウス操作はできないのですが、
マウス操作ができるEveryonePianoに関しては、Pythonのpyautogui.click()でボタンをクリックしてみたところ、マウスクリックだと問題なく受付するようで、仮想キーのみ受付できないのか、と考えました。

調べたところ、DirectXは仮想キーを受け付けないのではないか、といった記事も拝見し、仮想キー以外の方法でキーが押された事を渡す必要があるのだろうか…?と考えております。
https://teratail.com/questions/314989

もしご知見のある方がいればご教示いただきたいのですが、いかがでしょうか。

発生している問題・エラーメッセージ

上述の通り、仮想キーを送信しても反応しないです。

該当のソースコード

C#using

1using System.Collections.Generic; 2using System.Diagnostics; 3using System.Linq; 4using System.Runtime.InteropServices; 5using System.Text; 6using Microsoft.VisualBasic; 7 8namespace WindowSendKeyLib 9{ 10 class Program 11 { 12 //WMキー 13 public const int WM_LBUTTONDOWN = 0x201; 14 public const int WM_LBUTTONUP = 0x202; 15 public const int MK_LBUTTON = 0x0001; 16 public const int WM_KEYDOWN = 0x0100; 17 public const int WM_CHAR = 0x0102; 18 19 //WKキー 20 public const int VK_RETURN = 0x0D;//Enter 21 public const int VK_SHIFT = 0x10; 22 public const int VK_CONTROL = 0x11; 23 public const int VK_MENU = 0x12;//ALT 24 public const int VK_ESCAPE = 0x1B;//Esc 25 public const int VK_SPACE = 0x20; 26 public const int VK_LEFT = 0x25; 27 public const int VK_UP = 0x26; 28 public const int VK_RIGHT = 0x27; 29 public const int VK_DOWN = 0x28; 30 public const int VK_ZERO = 0x30; 31 32 public static int GWL_STYLE = -16; 33 34 /// <summary> 35 /// VM_CHARの時は使えるが、VM_KEYDOWNの時は使えないので、KEYDOWNの際はPostMessageを使う 36 /// </summary> 37 /// <param name="hWnd"></param> 38 /// <param name="Msg"></param> 39 /// <param name="wParam"></param> 40 /// <param name="lParam"></param> 41 /// <returns></returns> 42 [DllImport("user32.dll")] 43 public static extern int SendMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam); 44 45 /// <summary> 46 /// VM_KEYDOWNの時は使えないので、KEYDOWNの際はPostMessageを使う 47 /// </summary> 48 /// <param name="hWnd"></param> 49 /// <param name="Msg"></param> 50 /// <param name="wParam"></param> 51 /// <param name="lParam"></param> 52 /// <returns></returns> 53 [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] 54 private static extern bool PostMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam); 55 56 [DllImport("user32.dll")] 57 public static extern IntPtr FindWindowEx(IntPtr hWnd, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); 58 59 [DllImport("user32")] 60 public static extern int GetWindowLong(IntPtr hWnd, int nIndex); 61 62 [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 63 public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); 64 65 [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 66 public static extern int GetWindowTextLength(IntPtr hWnd); 67 68 [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 69 public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); 70 71 static void Main(string[] args) 72 { 73 //string appName = "notepad";//メモ帳 74 //string appName = "CalculatorApp";//電卓 75 //string appName = "sakura";//サクラエディタ 76 string appName = "everyonepiano";//ピアノ 77 //string appName = "RPG_RT";//RPGツクールのゲーム 78 try 79 { 80 // 対象ウィンドウのウィンドウハンドル 81 IntPtr mainWindowHandle = Process.GetProcessesByName(appName)[0].MainWindowHandle; 82 //対象ウィンドウをアクティブにしてから 83 Microsoft.VisualBasic.Interaction.AppActivate(appName); 84 85 if (mainWindowHandle == IntPtr.Zero) 86 { 87 return; 88 } 89 90 // ウィンドウクラスに変換 91 Window mainWindowClass = GetWindow(mainWindowHandle); 92 93 var all = GetAllChildWindows(mainWindowClass, new List<Window>()); 94 95 //メモ帳であればEditorコントロールなどがあるが、他者のアプリはどのオブジェクトが入力対象か外から不明なので、全ての子オブジェクトに対して一つずつキー入力操作を行ってみる 96 foreach (Window window in all) 97 { 98 Console.WriteLine("parent:" + mainWindowClass.Title + Environment.NewLine + "\tName:" + window.Title + Environment.NewLine + "\tClassName:" + window.ClassName + Environment.NewLine + "\tStyle:" + window.Style); 99 100 //// マウスを押して放す 101 //SendMessage(window.hWnd, WM_LBUTTONDOWN, MK_LBUTTON, 0x000A000A); 102 //SendMessage(window.hWnd, WM_LBUTTONUP, 0x00000000, 0x000A000A); 103 104 //下キーを押す 105 PostMessage(window.hWnd, WM_KEYDOWN, VK_DOWN, 0); 106 } 107 } 108 catch(Exception e) 109 { 110 Console.WriteLine("e:" + e.Message + Environment.NewLine + e.StackTrace); 111 } 112 113 //最後にコンソールで結果を見たいので、入力待機 114 Console.ReadLine(); 115 } 116 117 // 指定したウィンドウの全ての子孫ウィンドウを取得し、リストに追加する 118 public static List<Window> GetAllChildWindows(Window parent, List<Window> dest) 119 { 120 dest.Add(parent); 121 EnumChildWindows(parent.hWnd).ToList().ForEach(x => GetAllChildWindows(x, dest)); 122 return dest; 123 } 124 125 // 与えた親ウィンドウの直下にある子ウィンドウを列挙する(孫ウィンドウは見つけてくれない) 126 public static IEnumerable<Window> EnumChildWindows(IntPtr hParentWindow) 127 { 128 IntPtr hWnd = IntPtr.Zero; 129 while ((hWnd = FindWindowEx(hParentWindow, hWnd, null, null)) != IntPtr.Zero) { yield return GetWindow(hWnd); } 130 } 131 132 // ウィンドウハンドルを渡すと、ウィンドウテキスト(ラベルなど)、クラス、スタイルを取得してWindowsクラスに格納して返す 133 public static Window GetWindow(IntPtr hWnd) 134 { 135 int textLen = GetWindowTextLength(hWnd); 136 string windowText = null; 137 if (0 < textLen) 138 { 139 //ウィンドウのタイトルを取得する 140 StringBuilder windowTextBuffer = new StringBuilder(textLen + 1); 141 GetWindowText(hWnd, windowTextBuffer, windowTextBuffer.Capacity); 142 windowText = windowTextBuffer.ToString(); 143 } 144 145 //ウィンドウのクラス名を取得する 146 StringBuilder classNameBuffer = new StringBuilder(256); 147 GetClassName(hWnd, classNameBuffer, classNameBuffer.Capacity); 148 149 // スタイルを取得する 150 int style = GetWindowLong(hWnd, GWL_STYLE); 151 return new Window() { hWnd = hWnd, Title = windowText, ClassName = classNameBuffer.ToString(), Style = style }; 152 } 153 } 154 155 class Window 156 { 157 public string ClassName; 158 public string Title; 159 public IntPtr hWnd; 160 public int Style; 161 } 162} 163

Python

1import win32gui 2import win32con 3import pyautogui 4import time 5 6def foreground(): 7 hwnd = win32gui.FindWindow(None, "everyonepiano") 8 win32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST,0,0,0,0,win32con.SWP_NOMOVE | win32con.SWP_NOSIZE) 9 10 #対象アプリをアクティブにしてから 11 win32gui.SetForegroundWindow(hwnd) 12 13 #マウスなら動くのか確認するために入れた処理 こちらは動いた(音が出た) コメントアウトすると音が出なくなる 14 left, top, right, bottom = win32gui.GetWindowRect(hwnd) 15 pyautogui.moveTo(left+100, top + 220) 16 pyautogui.click() 17 time.sleep(1) 18 19 pyautogui.press('down') 20 time.sleep(1) 21 22 #pressだと駄目かと思い、念のためkeyDownも 23 pyautogui.keyDown('down') 24 time.sleep(1) 25 pyautogui.keyUp('down') 26 27if __name__ == '__main__': 28 foreground()

試したこと

念のため、以下の点を気を付けました。
・送信先のアプリはアクティブにした上で送信する
・C#でエンターや矢印などのキーを送信する際はSendMessageではなくPostMessageを使用

補足情報(FW/ツールのバージョンなど)

上述に記載したつもりなのですが、不足している情報がございましたらご指摘いただけますと幸いです。

よろしくお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

基本的にはSendInputでできると思いますが、Sending keys to a DirectX Gameの回答が参考になるかもしれません。

投稿2023/02/14 06:25

can110

総合スコア38266

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

deltamelon

2023/02/18 11:50

迅速なご回答、まことにありがとうございます。 ご丁寧に参考リンクまでつけていただき、とてもわかりやすく助かりました。 現在ご紹介いただいた情報を参考に実装中です。完成いたしましたらまたこちらに貼らせていただきます。 重ね重ね、ご回答いただきありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問