Pythonのclrモジュールを使用して.NET Framewokを動作させる
開発環境は、Windows 10 Pro + Python 3.7.6。
まずは空のフォームを表示するだけのプログラムを。
# -*- coding: utf-8 -*- import clr clr.AddReference("System.Windows.Forms") from System.Windows.Forms import Application, Form f1 = Form() f1.Text = "空のウィンドウ" Application.Run(f1)
実行してみると、以下のように、空のフォームが作成されました。
次にボタンをクリックすると、数字がカウントしていくプログラムを作成してみたいと思います。
# -*- coding: utf-8 -*- import clr clr.AddReference("System.Windows.Forms") from System.Windows.Forms import Application,Form,Label,Button from System.Drawing import Point f1 = Form() f1.Text = "カウントプログラム" l1 = Label() # 初期値 l1.Text = "0" l1.Location = Point(140,100) b1 = Button() b1.Text = "クリック" b1.Location = Point(110,150) # イベントハンドラの定義 def counter(form, event_args): l1.Text = str(int(l1.Text) + 1) # イベントハンドラの登録 b1.Click += counter f1.Controls.Add(l1) f1.Controls.Add(b1) Application.Run(f1)
以下は実行結果です。クリックするごとにカウントしていっているのが分かります。
今度は、clrモジュールではないのですが、この流れで、マウスカーソルを指定の位置に動かしてクリックするプログラムを作ります。これを実現するには、Pythonのctypesモジュールを利用して、Win32 APIを用いて、指定の位置にマウスカーソルが移動してクリックします。
# -*- coding: utf-8 -*- import ctypes ctypes.windll.user32.SetCursorPos(500,500) ctypes.windll.user32.mouse_event(0x2, 0,0,0,0) # 左クリックを押す ctypes.windll.user32.mouse_event(0x4, 0,0,0,0) # 左クリックを離す
実行してみると、ディスプレイ上のx座標が500、y座標が500の位置に移動して、その位置をクリックします。押す→離すを1セットとしないと、クリックとみなされません。
■参考リンク
IronPython.net / Documentation / .NET Integration
IronPython入門
IronPythonでWindows.Formを使えるようになりたい。 | tsuyuki.makoto
C#で指定した位置をクリックする - whoopsidaisies's diary
API 関数解説
【C++】WindowsAPIでマウス操作を検出する | のんぽぐ
【Python RPA】クリック・キーボード操作を検知する方法(ctypes.windll) | OFFICE54