Just a few hints:
To get a cursor position, use the static method
System.Windows.Forms.Cursor.Position
, see
http://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.aspx[
^].
Now, the problem is: how to capture the event of cursor motion?
If you want to response to the cursor motion when a mouse cursor stay within a form of your application, this is fairly simple: you need to handle the event
MouseMove
or override the method
OnMouseMove
.
If you need to be responsive to any motion of the mouse withing all of the screen, this is more difficult.
First approach is using system global hooks, but for this you will need to setup a hook in a native DLL, so you will need to go outside of .NET and write some native code. See
http://msdn.microsoft.com/en-us/library/windows/desktop/ms632589%28v=vs.85%29.aspx[
^]. You can setup a hook in C# code, but you need to do it in native code to make the hook global, see:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx[
^],
http://support.microsoft.com/kb/318804[
^],
http://msdn.microsoft.com/en-us/magazine/cc188966.aspx[
^].
Another, a trivial but compromised way would be polling (system-wide) mouse position. You can do it in a separate thread or in a timer, in some regular time interval, which means waste of CPU time and limited responsiveness at the same time. In both cases, you will need to notify the UI thread of the move. This is another problem:
You cannot call anything related to UI from non-UI thread. Instead, you need to use the method
Invoke
or
BeginInvoke
of
System.Windows.Threading.Dispatcher
(for both Forms or WPF) or
System.Windows.Forms.Control
(Forms only).
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[
^],
Problem with Treeview Scanner And MD5[
^].
See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[
^],
Control events not firing after enable disable + multithreading[
^].
—SA