user32.dllのGetCursorPosで画面上の座標を取得する。
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
namespace WpfApp
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
private extern static bool GetCursorPos(out POINT lpPoint);
private [[delegate]] void SetCursorPosDelegate(POINT point);
/// <summary>
/// コンストラクタ
/// </summary>
public MainWindow()
{
// コンポーネントの初期化
InitializeComponent();
Thread thread = new Thread(new ThreadStart(ViewCurrentCursorPos));
thread.IsBackground = true;
thread.Start();
}
/// <summary>
/// thread method
/// </summary>
private void ViewCurrentCursorPos()
{
POINT point = new POINT();
while (true)
{
// call user32.dll GetCursorPos method
if (GetCursorPos(out point))
{
SetCurosorPos(point);
}
Thread.Sleep(100);
}
}
/// <summary>
/// set cursor position to label content
/// </summary>
/// <param name="point"></param>
private void SetCurosorPos(POINT point)
{
if (LblCursorPos.Dispatcher.CheckAccess())
{
LblCursorPos.Content = string.Format("X:{0},Y:{1}", point.X, point.Y);
}
else
{
LblCursorPos.Dispatcher.Invoke(new SetCursorPosDelegate(SetCurosorPos), point);
}
}
/// <summary>
/// point
/// </summary>
public struct POINT
{
public int X { get; set; }
public int Y { get; set; }
}
}
}
最終更新:2014年01月25日 11:12