Skip to content

Instantly share code, notes, and snippets.

@bonprosoft
Created June 5, 2012 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bonprosoft/2876149 to your computer and use it in GitHub Desktop.
Save bonprosoft/2876149 to your computer and use it in GitHub Desktop.
VBでマウスカーソルの位置を取得するサンプル
Option Strict On
Imports System.Runtime.InteropServices
''' <summary>
''' 「ちょっとマウスカーソルの位置ってどうやって取得するのさ!」って言われたので、
''' マウスカーソルの座標を取得するサンプルです。
''' VBなら10分もあれば簡単に組めるよ!よ!
''' </summary>
''' <remarks>経過時間(m_Countrer)のところは、(VBのTimerが適当なため)だいぶずれています。
''' なので、StopWatchクラスとか使ってあげると、もっと精度が良くなると!
''' </remarks>
Public Class Form1
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Private Shared Function GetCursorPos(ByRef lpPoint As s_POINT) _
As Boolean
End Function
'コントロール
Friend WithEvents Log_txt As System.Windows.Forms.TextBox
'タイマー
Public WithEvents p_Timer As New Timer
'取得位置格納用
Dim m_X As Double = 0
Dim m_Y As Double = 0
'時間用カウンタ
Dim m_Counter As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'コントロールを設定
Log_txt.Dock = System.Windows.Forms.DockStyle.Fill
Log_txt.Location = New System.Drawing.Point(0, 0)
Log_txt.Multiline = True
Log_txt.Name = "Log_txt"
Log_txt.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.Controls.Add(Me.Log_txt)
'その他
p_Timer.Interval = 10
m_Counter = 0
p_Timer.Enabled = True
Log_txt.HideSelection = False
End Sub
'タイマーイベント
Private Sub p_Timer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles p_Timer.Tick
Dim p As s_POINT
m_Counter += 1
Try
GetCursorPos(p)
Catch ex As Exception
MsgBox("マウスカーソルの位置取得に失敗しました。" + vbCrLf + "処理を終了します。", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "警告")
End
End Try
If p.x <> m_X OrElse p.y <> m_Y Then
Log_txt.AppendText("Time:" + CStr(CDbl(m_Counter) / 100) + "/X:" + p.x.ToString _
+ "/Y:" + p.y.ToString + vbCrLf)
m_X = p.x
m_Y = p.y
End If
End Sub
End Class
Public Structure s_POINT
Public x As Integer
Public y As Integer
End Structure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment