How can I get cursor position on the form?
Asked Answered
W

1

6

I need to get cursor position on the form, how would I do that?

Weisburgh answered 20/4, 2011 at 5:31 Comment(0)
H
18

Pass Mouse.CursorPos to TForm.ScreenToClient().

Mouse.CursorPos is returned in the screen coordinate system. TForm.ScreenToClient() converts points into the form's client coordinate system.

In fact all TControl descendants offer the ScreenToClient() method, and its inverse, ClientToScreen(), to convert between coordinate systems.

Heterocercal answered 20/4, 2011 at 5:35 Comment(9)
You can shorten this with CalcCursorPos method which becomes unprotected in the unit where the TForm descendant is defined. This method exists even in Delphi 7...Incursion
What unit do I need to put in the uses so that Mouse will be known to the compiler ?Unsecured
@Guido I just did a websearch to find out. Or you can just search the VCL source code. Rather than telling you I'll let you do one of these.Heterocercal
Well if I could find it easy with a websearch I would not have asked here. The documentation mentions a lot of obvious stuff, but nothing about what you need to add to your uses. Nothing personal, but I see a lot of answers and examples on the web that forget to mention someting trivial that keeps people from being able to use it. I just wanted to mention this to get if off my chest. Good evening to you sirUnsecured
@guido I didnt know off the top of my head but I found it straight away with a websearch. Include the keywords delphi and docwiki in tuor search and you will find it too.Heterocercal
This seems to be not working correctly on High DPI configuration introduced in Delphi 11. When I have selected GDI scaling, ``ScreenToClient(Mouse.CursorPos)` reports that mouse is at 980, 630 while my form reports its width and height as 640x480 (mouse is outside the boundaries of form), however CalcCursorPos seems to report it correctly.Whisk
@Whisk why are you using GDI scaling. Why aren't you using per monitor v2?Heterocercal
I tried that, and it doesn't work correctly on graphic only components (TGraphics for example). This is more obvious when each monitor has different DPI scale (e.g. 100 and 150). In fact I tried every possible option and GDI scaling was the only one that worked fine, even though it is a little bluryWhisk
@Whisk you just need to fix the componentsHeterocercal

© 2022 - 2024 — McMap. All rights reserved.