LoginSignup
2
1

More than 1 year has passed since last update.

Python - ctypesのwindllでマウスの位置を取得する

Posted at

まぁpyautoguiを使って取得すればいいだけの話なんですけど、自分の環境だとpyautiguiをインポートしたときに急に高DPI対応になったりして、wxPythonだと高DPI対応にしたときに謎に表示がおかしくなるのが嫌なので今回はそれ以外の方法でマウス位置を取得する方法を紹介します。
(あとpyautoguiインポートするのに少し時間かかる)

※Windowsで実行しないとエラーになる場合があります。

import ctypes
class POINT(ctypes.Structure):
    _fields_ = [("x", ctypes.c_long),
                ("y", ctypes.c_long)]
def GetPosition():
    cursor = POINT()
    ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))
    return (cursor.x, cursor.y)
print(GetPosition())

一応このコードで取得できますが、これは高DPIに対応していないときの位置となっています。

そのため、マウスを画面の一番右下において実行してみると、

(1535, 863)

となってしまいます。
自分みたいに、wxPythonなどで高DPIじゃないソフトをつくるような人ならいいんですけど、そうじゃない場合は以下のようにコードを書くと正確に測れます。

#高DPI対応にしてから、取得
import ctypes
try:
    ctypes.windll.shcore.SetProcessDpiAwareness(True)
except:
    pass
class POINT(ctypes.Structure):
    _fields_ = [("x", ctypes.c_long),
                ("y", ctypes.c_long)]
def GetPosition():
    cursor = POINT()
    ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))
    return (cursor.x, cursor.y)
print(GetPosition())
(1919, 1079)

(なぜか一つずつ下がっていますが、正確に取得できています。)

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1