Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Delphi программирование > Общие вопросы Delphi
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 20.07.2011, 12:58   #1
AlexDn
Пользователь
 
Регистрация: 02.10.2009
Сообщений: 93
Вопрос Снять координаты курсора

Вот понадобилось снять координаты курсора мышки с рабочего стола..
если делать
Код:
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  foo: TPoint;
begin
  GetCursorPos(foo);
  ShowMessage('(' + IntToStr(foo.X) + ' ,' + IntToStr(foo.Y) + ')');
end;
то соответственно снимается положение только на форме.. говорят чтобы снять с раб стола нужно делать хук мыши SetWindowsHook, параметр WH_MOUSE. подскажите плиз где что можно почитать об этом для делфи, а то везде только си....
AlexDn вне форума Ответить с цитированием
Старый 20.07.2011, 13:40   #2
grafgrial
Просто хороший
Форумчанин
 
Аватар для grafgrial
 
Регистрация: 26.03.2010
Сообщений: 562
По умолчанию

Код:
var
  rPos:Tpoint;
  x,y:integer;

GetCursorPos(rpos);
x:=rpos.x;
y:=rpos.y;
Label1.Caption:=inttostr(x);
Label2.Caption:=inttostr(y);
в свое время искал, все на дельфи но только на весь рабочий стол, а на форме не мог найти..

а ты поставь в таймере
Помог, нажми весы слева
grafgrial вне форума Ответить с цитированием
Старый 20.07.2011, 14:14   #3
AlexDn
Пользователь
 
Регистрация: 02.10.2009
Сообщений: 93
По умолчанию

grafgrial, про таймер интересная идея!.. интересно, можно ли ещё к какому компоненту привязать, чтоб он на форму не обращал внимание?..
AlexDn вне форума Ответить с цитированием
Старый 20.07.2011, 14:29   #4
Прик
Форумчанин
 
Регистрация: 08.09.2010
Сообщений: 880
По умолчанию

Вот перепечатка из Delphi World 6. Проверено - работает.
В примере все события журналируются в листбоксе. Переделать для своих нужд не представляет проблемы.
Код:
Ловить события мышки вне вашего приложения 
Оформил: DeeCo Автор: http://www.swissdelphicenter.ch 

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    ApplicationEvents1: TApplicationEvents;
    Button_StartJour: TButton;
    Button_StopJour: TButton;
    ListBox1: TListBox;
    procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
    procedure Button_StartJourClick(Sender: TObject);
    procedure Button_StopJourClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
   private
     FHookStarted : Boolean;
   public
   end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

var
  JHook: THandle;

 // The JournalRecordProc hook procedure is an application-defined or library-defined callback 
// function used with the SetWindowsHookEx function. 
// The function records messages the system removes from the system message queue. 
// A JournalRecordProc hook procedure does not need to live in a dynamic-link library. 
// A JournalRecordProc hook procedure can live in the application itself. 

// WH_JOURNALPLAYBACK Hook Function 

//Syntax 

// JournalPlaybackProc( 
// nCode: Integer;  {a hook code} 
// wParam: WPARAM;  {this parameter is not used} 
// lParam: LPARAM  {a pointer to a TEventMsg structure} 
// ): LRESULT;  {returns a wait time in clock ticks} 

function JournalProc(Code, wParam: Integer; var EventStrut: TEventMsg): Integer; stdcall;
 var
   Char1: PChar;
   s: string;
begin
   {this is the JournalRecordProc}
  Result := CallNextHookEx(JHook, Code, wParam, Longint(@EventStrut));
   {the CallNextHookEX is not really needed for journal hook since it it not 
  really in a hook chain, but it's standard for a Hook}
  if Code < 0 then Exit;

   {you should cancel operation if you get HC_SYSMODALON}
  if Code = HC_SYSMODALON then Exit;
  if Code = HC_ACTION then begin
     { 
    The lParam parameter contains a pointer to a TEventMsg 
    structure containing information on 
    the message removed from the system message queue. 
    }
     s := '';

     if EventStrut.message = WM_LBUTTONUP then
       s := 'Left Mouse UP at X pos ' +
         IntToStr(EventStrut.paramL) + ' and Y pos ' + IntToStr(EventStrut.paramH);

     if EventStrut.message = WM_LBUTTONDOWN then
       s := 'Left Mouse Down at X pos ' +
         IntToStr(EventStrut.paramL) + ' and Y pos ' + IntToStr(EventStrut.paramH);

     if EventStrut.message = WM_RBUTTONDOWN then
       s := 'Right Mouse Down at X pos ' +
         IntToStr(EventStrut.paramL) + ' and Y pos ' + IntToStr(EventStrut.paramH);

     if (EventStrut.message = WM_RBUTTONUP) then
       s := 'Right Mouse Up at X pos ' +
         IntToStr(EventStrut.paramL) + ' and Y pos ' + IntToStr(EventStrut.paramH);

     if (EventStrut.message = WM_MOUSEWHEEL) then
       s := 'Mouse Wheel at X pos ' +
         IntToStr(EventStrut.paramL) + ' and Y pos ' + IntToStr(EventStrut.paramH);

     if (EventStrut.message = WM_MOUSEMOVE) then
       s := 'Mouse Position at X:' +
         IntToStr(EventStrut.paramL) + ' and Y: ' + IntToStr(EventStrut.paramH);

     if s <> '' then
        Form1.ListBox1.ItemIndex :=  Form1.ListBox1.Items.Add(s);
   end;
 end;

 procedure TForm1.Button_StartJourClick(Sender: TObject);
 begin
   if FHookStarted then
   begin
     ShowMessage('Mouse is already being Journaled, can not restart');
     Exit;
   end;
   JHook := SetWindowsHookEx(WH_JOURNALRECORD, @JournalProc, hInstance, 0);
   {SetWindowsHookEx starts the Hook}
   if JHook > 0 then
   begin
     FHookStarted := True;
   end
   else
     ShowMessage('No Journal Hook availible');
 end;

 procedure TForm1.Button_StopJourClick(Sender: TObject);
 begin
   FHookStarted := False;
   UnhookWindowsHookEx(JHook);
   JHook := 0;
 end;

 procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;
   var Handled: Boolean);
 begin
   {the journal hook is automaticly camceled if the Task manager 
  (Ctrl-Alt-Del) or the Ctrl-Esc keys are pressed, you restart it 
  when the WM_CANCELJOURNAL is sent to the parent window, Application}
   Handled := False;
   if (Msg.message = WM_CANCELJOURNAL) and FHookStarted then
     JHook := SetWindowsHookEx(WH_JOURNALRECORD, @JournalProc, 0, 0);
 end;

 procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
 begin
   {make sure you unhook it if the app closes}
   if FHookStarted then
     UnhookWindowsHookEx(JHook);
 end;

 end.
Прик вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Координаты курсора WINAPI konstahntin Помощь студентам 0 14.05.2011 09:58
RichEdit Координаты Курсора nusik Общие вопросы Delphi 5 25.04.2009 23:24
Координаты текстового курсора DeKot Общие вопросы Delphi 4 07.03.2009 20:47
Координаты курсора на изображении Ciberal Мультимедиа в Delphi 2 28.10.2008 19:33
Координаты курсора Haster Win Api 8 06.08.2007 12:04