我有一个图形应用程序,用鼠标移动图形对象。
在某些情况下,物体会停止移动。我还需要停止移动鼠标光标。
有可能吗? MousePosition
属性似乎在ReadOnly中。
例如
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.X > 100)
{
Cursor.Position = new Point(100, Cursor.Position.Y);
}
}
}
编辑,第二个版本,但是光标不是“稳定” - 闪烁:
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.X > 100)
{
Point mousePosition = this.PointToClient(Cursor.Position);
mousePosition.X = 100;
Point newScreenPosition = this.PointToScreen(mousePosition);
Cursor.Position = newScreenPosition;
}
}
答案 0 :(得分:3)
您可以通过PInvoke使用ClipCursor功能。如果bouding矩形足够小,鼠标将不会移动。
修改
一个例子:
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct RECT {
public int left;
public int top;
public int right;
public int bottom;
};
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32.dll")]
static extern bool ClipCursor([In()]ref RECT lpRect);
[DllImport("user32.dll")]
static extern bool ClipCursor([In()]IntPtr lpRect);
private bool locked = false;
private void button1_Click(object sender, EventArgs e)
{
if (locked) {
ClipCursor(IntPtr.Zero );
}
else {
RECT r;
Rectangle t = new Rectangle(0, 0, 100, this.ClientSize.Height);
t = this.RectangleToScreen(t);
r.left = t.Left;
r.top = t.Top;
r.bottom = t.Bottom;
r.right = t.Right;
ClipCursor(ref r);
}
locked = !locked;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
答案 1 :(得分:2)
您是否尝试过使用Cursor.Position
?
E.g。
Cursor.Position = new Point(100, 100);
您可以将其设置为恒定值(如Vulcan所说)。