Автор:
Andrew Pociu | добавлено: 16.04.2011, 15:18 | просмотров: 14857 (1+) | комментариев:
0 | рейтинг:
x5
Пример демонстрирует, как при помощи C# получить позицию курсора мышки на экране. Также в программе ведется пробег мышки в пикселях.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace CursorPosition
{
public partial class frmMain : Form
{
// объявляем API
[DllImport("user32.dll")]
static extern bool GetCursorPos(ref Point lpPoint);
// глобальные переменные, в которых будут храниться координаты
static protected long totalPixels = 0;
static protected int currX;
static protected int currY;
static protected int diffX;
static protected int diffY;
public frmMain()
{
InitializeComponent();
}
private void tmrDef_Tick(object sender, EventArgs e)
{
// обновление информации происходит каждые 10 мс
Point defPnt = new Point();
// заполняем defPnt информацией о координатах мышки
GetCursorPos(ref defPnt);
// выводим информацию в окно
lblCoordX.Text = "X = " + defPnt.X.ToString();
lblCoordY.Text = "Y = " + defPnt.Y.ToString();
// если курсор перемещался
if (diffX != defPnt.X | diffY != defPnt.Y)
{
// рассчитываем на сколько пикселей
diffX = (defPnt.X - currX);
diffY = (defPnt.Y - currY);
if (diffX < 0)
{
diffX *= -1;
}
if (diffY < 0)
{
diffY *= -1;
}
// обновляем счетчик пробега мышки
totalPixels += diffX + diffY;
// выводим информацию о пробеге
lblTravel.Text = "You have traveled " + totalPixels + " pixels";
}
// запоминаем текущие координаты, для расчета пробега
currX = defPnt.X;
currY = defPnt.Y;
}
private void btnReset_Click(object sender, EventArgs e)
{
totalPixels = 0;
}
}
}