当鼠标在窗体上滑动时, 可以触发窗体的FormMouseMove方法, 代码如下:
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::FormMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { Label1->Caption = X; Label2->Caption = Y; } //---------------------------------------------------------------------------但是, 上述方法是有缺陷的, 因为, Label1和Label2在窗体上, 当鼠标滑过他们时候, 窗体被挡住, 此时窗体方法不被调用, 故有缺陷, 而且, 更关键的是, 上述位置是相对于窗体的位置。 那怎么办呢? 我们考虑用定时器来做, 我们把定时器的定时时间间隔设置为10ms吧, 程序如下:
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::Timer1Timer(TObject *Sender) { Label1->Caption = Mouse->CursorPos.x; Label2->Caption = Mouse->CursorPos.y; } //---------------------------------------------------------------------------好了, 这就解决了上面的问题。 当然, 也可以用API来获取, 如下:
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::Timer1Timer(TObject *Sender) { POINT pt; GetCursorPos(&pt); Label1->Caption = pt.x; Label2->Caption = pt.y; } //---------------------------------------------------------------------------
Windows这么强大, 你就不要担心获取不了鼠标当前位置了。