Форум программистов «Весельчак У»
  *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

  • Рекомендуем проверить настройки временной зоны в вашем профиле (страница "Внешний вид форума", пункт "Часовой пояс:").
  • У нас больше нет рассылок. Если вам приходят письма от наших бывших рассылок mail.ru и subscribe.ru, то знайте, что это не мы рассылаем.
   Начало  
Наши сайты
Помощь Поиск Календарь Почта Войти Регистрация  
 
Страниц: [1]   Вниз
  Печать  
Автор Тема: Ударим автопробегом по бездорожью!!!!  (Прочитано 12620 раз)
0 Пользователей и 1 Гость смотрят эту тему.
Dr.Snipper
Гость
« : 16-12-2004 18:37 » 

Можно ли как ибудь конторолировать движение мыши. Например показывать сколько пикселей(или лучше сантиметров(мечты... мечты...)) прошла мышь.

P.S.
Можно ли определить координаты в сей момент(X и Y)
Записан
Finch
Спокойный
Администратор

il
Offline Offline
Пол: Мужской
Пролетал мимо


« Ответ #1 : 17-12-2004 14:37 » 

API Функция для определения координат :
Цитата
The GetCursorPos function retrieves the cursor's position, in screen coordinates.

BOOL GetCursorPos(

    LPPOINT lpPoint    // address of structure for cursor position  
   );   
 

Parameters

lpPoint

Points to a POINT structure that receives the screen coordinates of the cursor.

 

Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The cursor position is always given in screen coordinates and is not affected by the mapping mode of the window that contains the cursor.
The calling process must have WINSTA_READATTRIBUTES access to the window station.
Записан

Не будите спашяго дракона.
             Джаффар (Коша)
ixania
Гость
« Ответ #2 : 17-12-2004 16:02 » 

//Finch misi a ne cursora Ага

Vot eto mojet pomoch

GetMouseMovePointsEx Function

The GetMouseMovePointsEx function retrieves a history of up to 64 previous coordinates of the mouse or pen.

Syntax

int GetMouseMovePointsEx(      


    UINT cbSize,
    LPMOUSEMOVEPOINT lppt,
    LPMOUSEMOVEPOINT lpptBuf,
    int nBufPoints,
    DWORD resolution
);

Parameters
cbSize
[in] Specifies the size, in bytes, of the MOUSEMOVEPOINT structure.
lppt
[in] Pointer to a MOUSEMOVEPOINT structure containing valid mouse coordinates (in screen coordinates). It may also contain a time stamp.

The GetMouseMovePointsEx function searches for the point in the mouse coordinates history. If the function finds the point, it returns the last nBufPoints prior to and including the supplied point.

If your application supplies a time stamp, the GetMouseMovePointsEx function will use it to differentiate between two equal points that were recorded at different times.

An application should call this function using the mouse coordinates received from the WM_MOUSEMOVE message and convert them to screen coordinates.
lpptBuf
[in] Pointer to a buffer that will receive the points. It should be at least cbSize* nBufPoints in size.
nBufPoints
[in] Specifies the number of points to retrieve.
resolution
[in] Specifies the resolution desired. This parameter can be one of the following values.
GMMP_USE_DISPLAY_POINTS
Retrieves the points using the display resolution.
GMMP_USE_HIGH_RESOLUTION_POINTS
Retrieves high resolution points. Points can range from zero to 65,535 (0xFFFF) in both x- and y-coordinates. This is the resolution provided by absolute coordinate pointing devices such as drawing tablets.

Return Value

If the function succeeds, the return value is the number of points in the buffer. Otherwise, the function returns 1. For extended error information, your application can call GetLastError. The GetLastError function may return the following error code.
Value   Meaning   
GMMP_ERR_POINT_NOT_FOUND   The point specified by lppt could not be found or is no longer in the system buffer.   



Remarks

The system retains the last 64 mouse coordinates and their time stamps. If your application supplies a mouse coordinate to GetMouseMovePointsEx and the coordinate exists in the system's mouse coordinate history, the function retrieves the specified number of coordinates from the systems' history. You can also supply a time stamp, which will be used to differentiate between identical points in the history.

The GetMouseMovePointsEx function will return points that eventually were dispatched not only to the calling thread but also to other threads.

GetMouseMovePointsEx may fail or return erroneous values in the following cases:

If negative coordinates are passed in the MOUSEMOVEPOINT structure.
If GetMouseMovePointsEx retrieves a coordinate with a negative value.

These situations can occur if multiple monitors are present. To correct this, first call GetSystemMetrics to get the following values:

SM_XVIRTUALSCREEN,
SM_YVIRTUALSCREEN,
SM_CXVIRTUALSCREEN, and
SM_CYVIRTUALSCREEN.

Then, for each point that is returned from GetMouseMovePointsEx, perform the following transform:

int nVirtualWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN) ;
int nVirtualHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN) ;
int nVirtualLeft = GetSystemMetrics(SM_XVIRTUALSCREEN) ;
int nVirtualTop = GetSystemMetrics(SM_YVIRTUALSCREEN) ;
int cpt = 0 ;
int mode = GMMP_USE_DISPLAY_POINTS ;

MOUSEMOVEPOINT mp_in ;
MOUSEMOVEPOINT mp_out[64] ;

ZeroMemory(&mp_in, sizeof(mp_in)) ;
mp_in.x = pt.x & 0x0000FFFF ;//Ensure that this number will pass through.
mp_in.y = pt.y & 0x0000FFFF ;
cpt = GetMouseMovePointsEx(&mp_in, &mp_out, 64, mode) ;

for (int i = 0; i < cpt; i++)
{
   switch(mode)
   {
   case GMMP_USE_DISPLAY_POINTS:
      if (mp_out.x > 32767)
         mp_out.x -= 65536 ;
      if (mp_out.y > 32767)
         mp_out.y -= 65536 ;
      break ;
   case GMMP_USE_HIGH_RESOLUTION_POINTS:
      mp_out.x = ((mp_out.x * (nVirtualWidth - 1)) - (nVirtualLeft * 65536)) / nVirtualWidth ;
      mp_out.y = ((mp_out.y * (nVirtualHeight - 1)) - (nVirtualTop * 65536)) / nVirtualHeight ;
      break ;
   }
}

Function Information
Minimum DLL Version   user32.dll   
Header   Declared in Winuser.h, include Windows.h   
Import library   User32.lib   
Minimum operating systems   Millennium, Windows 2000
Записан
x77
Модератор

ro
Offline Offline
Пол: Мужской
меняю стакан шмали на обратный билет с Марса.


« Ответ #3 : 17-12-2004 16:13 » new

Finch, коллега, позволю себе не согласиться Улыбаюсь врядли ли речь идёт о сомнительном удовольствии считать автопробег только по собственному окну, следовательно, здесь понадобятся хуки.

Dr.Snipper, итак. начнём с того, что хук есть некая вещь, которую можно прицепить на некое событие в системе. очень грубый аналог - евенты в дельфи, только хуки могут выстраивать в целые цепочки, и умеют работать на уровне не только "своего" приложения, но и системы в целом.

поскольку хук будет глобальным, его придётся засунуть в dll. выглядеть она будет примерно так:

Код:

library hooks;

uses
  SysUtils,
  Classes,
  Windows,
  Messages;

|$R *.RES"

| Объявим собственное сообщение, Которое мы будем отсылать основному приложению в момент движения мыши по экрану "

const
  WM_MouseEvent = WM_USER + 100;

| Определим структуру, которая будет возвращать информацию о положении мыши )подробности - Win32 SDK: "

type
  TMouseHookStruct = record
    Pt{ TPoint;
    Wnd{ hWND;
    HitTestCode{ word;
    dwExtraInfo{ dword;
  end;
  PMouseStructRect = ^TMouseHookStruct;

| Определим переменную, дескриптор хука "

var
  hMouse{ hHOOK;

| Определим процедуру, которая будет вызываться при сработке хука "

function MouseProc )Code, wParam, lParam{ integer:{ integer; stdcall;
begin
  | Проверяем, что событием, вызвавшим хук было движение мыши, а не щелчок, к примеру, или ещё какая белиберда "
  if )Code = HC_ACTION: and )wParam = WM_MOUSEMOVE: then begin
    with PMouseHookStruct )lParam:^ do begin
      | Посылаем основному приложению сообщение, и в этом же сообщении передаём текущие координаты мыши "
      SendMessage)FindWindow)'TForm1', 'Form1':, WM_MouseEvent, Pt.X, Pt.Y:;
      Result {= 0;
    end;
  end else | в противном случае вызываем следующий по цепочке хук "
    Result {= CallNextHookEx )hMouse, Code, wParam, lParam:;
end;

| Собственно, Установка хука на все события от мыши "
procedure SetMouseHook; stdcall;
begin
  hMouse {= SetWindowsHookEx )WH_MOUSE, @MouseProc, hInstance, 0:;
end;

| ну и снятие, соответственно "

procedure UnsetMouseHook; stdcall;
begin
  UnhookWindowsHookEx )hMouse:;
end;

exports
  SetMouseHook,
  UnsetMouseHook;

begin
end.


это основная часть. само приложение будет довольно простым, я его даже комментить не буду:

Код:

unit main;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  ExtCtrls, StdCtrls;

const
  WM_MouseEvent = WM_USER + 100;

type
  TForm1 = class)TForm:
    Label1{ TLabel;
    Timer1{ TTimer;
    procedure FormCreate)Sender{ TObject:;
    procedure FormDestroy)Sender{ TObject:;
    procedure WmMouseEvent )var Msg{ TMessage:; message WM_MouseEvent;
  private
    | Private declarations "
  public
    | Public declarations "
  end;

var
  Form1{ TForm1;

procedure SetMouseHook; stdcall; external 'hooks.dll';
procedure UnsetMouseHook; stdcall; external 'hooks.dll';

implementation

|$R *.DFM"

procedure TForm1.FormCreate)Sender{ TObject:;
begin
  SetMouseHook;
end;

procedure TForm1.FormDestroy)Sender{ TObject:;
begin
  UnsetMouseHook;
end;

procedure TForm1.WmMouseEvent)var Msg{ TMessage:;
begin
  Label1.Caption {= Format )'%d{%d', [Msg.wParam, Msg.lParam(:;
end;

end.


ну а тебе осталось в последней процедуре запоминать прошлые координаты и вычислять сам пробег по теореме Пифагора. это будет пробег в пикселях. перевести его в сантиметры нельзя, а вот в дюймы можно - см. свойство формы PixelsPerInch. ну а сколько в дюйме сантиметров - сам знаешь, надеюсь Ага
Записан

Finch
Спокойный
Администратор

il
Offline Offline
Пол: Мужской
Пролетал мимо


« Ответ #4 : 18-12-2004 11:37 » 

ixania, Объясни пожалуйста в чем разница между координатами курсора мыши на экране и курсора. Я не говорю о глобальных координатах мыши (как физического объекта) относительно координатной системы солнца. Тут даже система GPS может не помочь. Улыбаюсь Если ты имееш ввиду курсор редактирования, то для него сушествует своя функция:
Цитата

The GetCaretPos function copies the caret's position, in client coordinates, to the specified POINT structure.

BOOL GetCaretPos(

    LPPOINT lpPoint    // address of structure to receive coordinates
   );   
 

Parameters

lpPoint

Points to the POINT structure that is to receive the client coordinates of the caret.

 

Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The caret position is always given in the client coordinates of the window that contains the caret.


x77, Та функция, которую я дал, дает координаты не относительно окна программы, а относительно координат экрана. По крайней мере так написано в описании
Цитата

The GetCursorPos function retrieves the cursor's position, in screen coordinates.

Цитата

The cursor position is always given in screen coordinates and is not affected by the mapping mode of the window that contains the cursor.

т.е. эта функция возрашает текушие координаты курсора на данный момент относительно координат экрана.
Записан

Не будите спашяго дракона.
             Джаффар (Коша)
x77
Модератор

ro
Offline Offline
Пол: Мужской
меняю стакан шмали на обратный билет с Марса.


« Ответ #5 : 19-12-2004 11:27 » 

Finch, я понимаю. просто как ты собираешься отлавливать сам факт перемещения мыши? таймером?
Записан

ixania
Гость
« Ответ #6 : 19-12-2004 17:15 » 

2Finch а знаешь ты правб я невнимательно МСДН прочел. Забираю свои слова обратно насчет твоей неправоты.
Записан
x77
Модератор

ro
Offline Offline
Пол: Мужской
меняю стакан шмали на обратный билет с Марса.


« Ответ #7 : 19-12-2004 17:20 » 

что-то я не врубаюсь совсем, о чём речь идёт.

Сниппер, поясни, что тебе нужно, плз. программку типа "мышометра", показывающую сколько пикселей пробежала мышь, или просто определить её положение на экране?
Записан

Dr.Snipper
Гость
« Ответ #8 : 19-12-2004 18:23 » 

Мне надо знать координаты КУРСОРА ОТНОСИТЕЛЬНО ВСЕГО ЭКРАНА
Записан
x77
Модератор

ro
Offline Offline
Пол: Мужской
меняю стакан шмали на обратный билет с Марса.


« Ответ #9 : 19-12-2004 18:27 » 

и всё? показывать, сколько пикселей прошла мышь, ты уже передумал? тогда хватит GetCursorPos. а если требуется отлавливать перемещение мыши в системе (не только в своей программе), то хуки.
Записан

Finch
Спокойный
Администратор

il
Offline Offline
Пол: Мужской
Пролетал мимо


« Ответ #10 : 19-12-2004 19:25 » 

x77, Есть еше один способ отлавливать перемешение мыши, но у него есть небольшой минус. Через функцию
Цитата

The SetCapture function sets the mouse capture to the specified window belonging to the current thread. Once a window has captured the mouse, all mouse input is directed to that window, regardless of whether the cursor is within the borders of that window. Only one window at a time can capture the mouse.

If the mouse cursor is over a window created by another thread, the system will direct mouse input to the specified window only if a mouse button is down.

HWND SetCapture(

    HWND hWnd    // handle of window to receive mouse capture
   );   
 

Parameters

hWnd

Identifies the window in the current thread that is to capture the mouse.

 

Return Values

If the function succeeds, the return value is the handle of the window that had previously captured the mouse. If there is no such window, the return value is NULL.

Remarks

Only the foreground window can capture the mouse. When a background window attempts to do so, the window receives messages only for mouse events that occur when the cursor hot spot is within the visible portion of the window. Also, even if the foreground window has captured the mouse, the user can still click another window, bringing it to the foreground.
When the window no longer requires all mouse input, the thread that created the window should call the ReleaseCapture function to release the mouse.

This function cannot be used to capture mouse input meant for another process.
Windows 95: Calling this function causes the window that is losing the mouse capture to receive a WM_CAPTURECHANGED message.

Ставится перехватчик на мышь. И все сообшения идут на окно, на которое выставлен перехватчик. Есть правда два минуса. Первый минус. Что сообшения потом желательно транслировать другим окнам. И второй - Очень легко переключить перехватчик. Хотя окно оповешается, что перехватчик переключен.
Записан

Не будите спашяго дракона.
             Джаффар (Коша)
x77
Модератор

ro
Offline Offline
Пол: Мужской
меняю стакан шмали на обратный билет с Марса.


« Ответ #11 : 19-12-2004 19:33 » 

Finch, у неё есть и третий минус: она работает только на видимой части окна. твоё окно должно быть активным или, как минимум, видимым.

я решал задачу подсчёта общего пробега. т.е. запустили невидимый сервис и он нам считает все движения мыши по экрану. насколько я понял, автору сабжа это нафиг не надо, так что умываю руки Улыбаюсь
Записан

Страниц: [1]   Вверх
  Печать  
 

Powered by SMF 1.1.21 | SMF © 2015, Simple Machines