Mutil monitor mouse tracking
I have a need to track mouse position. While I have attempted several ways of doing this, I never am able to follow/capture the position if the mouse is on another monitor.
[DllImport("user32.dll")]
public static extern bool GetCursorPos(ref Point pt);
[DllImport("user32.dll")]
public static extern bool GetCursorInfo(out CURSORINFO pci);
public void GetPosition(out int X, out int Y)
{
Point pt = new Point(0, 0);
X = Y = 0;
if (MouseMonitor.GetCursorPos(ref pt))
{
X = pt.X;
Y = pt.Y;
}
This works but only on one screen. I also read that I might try GetCursorInfo. I have attempted this but it always comes back false. [DllImport("user32.dll")] public static extern bool GetCursorInfo(out CURSORINFO pci);
Any suggestions? My goal is to track mouse position (outsid开发者_运维问答e of my own app) regardless of what screen it is on.
Your sample code works for me on my dual-monitor system...
You can actually simplify things quite a bit by using the .NET Framework: the System.Windows.Forms.Cursor class has a static Position property.
For example, I created a new Windows Forms project and then dragged a System.Windows.Forms.Timer onto the form. I set the Enabled property to true, and added this code to the Tick event:
this.Text = string.Format("{0}, {1}", Cursor.Position.X, Cursor.Position.Y);
Ran the project and it worked as expected on both my monitors...
Use DWORD GetMessagePos() - it gives you the last windows message mouse position. But be careful, it returns DWORD, but inside there are two SHORTS (16-bit signed ints) packed. So LOWORD/HIWORD macros (or C# respective) won't work.
http://msdn.microsoft.com/en-us/library/ms644938(VS.85).aspx
精彩评论