【Python】マウス左クリックした位置の画面座標を取得しコンソールに出力
win32apiの
user32.GetCursorPosとuser32.GetAsyncKeyStateを組み合わせて
左クリックした位置の座標を取得し,コンソールに出力するプログラム
下記は2回クリックして1回目が左上,2回目を右下とする矩形の座標を呼び出し元に返すプログラム
# -*- coding: utf-8 -*- import ctypes import time def get_rectcordinate(): # 構造体を定義 class _pointer(ctypes.Structure): _fields_ = [ ('x', ctypes.c_long), ('y', ctypes.c_long), ] # 構造体を初期化 point_topleft = _pointer() point_bottomright = _pointer() ## 監視領域をクリックして取得------------------------------------------------------------------ vk_leftbutton = 0x01 #マウス左ボタン Virtual Keyboad vk_esc = 0x1B # ESC Virtual Keyboad # 監視領域の左上をクリック print u"Click Leftbutton for Watch Area of Top-Left" while 1: if ctypes.windll.user32.GetAsyncKeyState(vk_leftbutton) == 0x8000: #0b1000 0000 0000 0000 # 構造体のポインタを引数で渡す(参照渡し) ctypes.windll.user32.GetCursorPos(ctypes.byref(point_topleft)) print "X:" + str(point_topleft.x) + ", Y:" + str(point_topleft.y) + "\n\r" break elif ctypes.windll.user32.GetAsyncKeyState(vk_esc) == 0x8000: print "Canceled" break # 監視領域の右下をクリック time.sleep(0.2) print u"Click Leftbutton for Watch Area of Bottom-right" while 1: if ctypes.windll.user32.GetAsyncKeyState(vk_leftbutton) == 0x8000: #0b1000 0000 0000 0000 # 構造体のポインタを引数で渡す(参照渡し) ctypes.windll.user32.GetCursorPos(ctypes.byref(point_bottomright)) print "X:" + str(point_bottomright.x) + ", Y:" + str(point_bottomright.y) + "\n\r" break elif ctypes.windll.user32.GetAsyncKeyState(vk_esc) == 0x8000: print "Canceled" break return ((point_topleft.x, point_topleft.y, point_bottomright.x, point_bottomright.y))