如何取得鼠标的位置坐标?
百度了没找到答案,我想用C#实现下面的功能。
需求是这样的:
1、鼠标不在窗体内;
2、窗体不实际获的;
3、每当鼠标移动时,就执行相应代码。
该怎么做得到鼠标位置??
------解决方案--------------------
详细代码:
1.安装钩子:
const int WM_MOUSEMOVE = 0x0200; //移动鼠标
const int MouseLL = 14;
public void Start()
{
if (hMouseHook == 0)
{
MouseHookProcedure = new HookProc(MouseHookProc);
using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())
using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule)
hMouseHook = SetWindowsHookEx(MouseLL, MouseHookProcedure, GetModuleHandle(curModule.ModuleName), 0);
if (hMouseHook == 0)
{
Stop();
throw new Exception("Set GlobalKeyboardHook failed!");
}
}
}
public void Stop()
{
bool retMouse = true;
if (hMouseHook != 0)
{
retMouse = UnhookWindowsHookEx(hMouseHook);
hMouseHook = 0;
}
if (!retMouse)
throw new Exception("Unload GlobalKeyboardHook failed!");
}
2.钩子函数:
private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == WM_MOUSEMOVE)
{
GetCursorPos(ref p);
textBox1.Text = p.X.ToString();
textBox2.Text = p.Y.ToString();
}
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}