如何在Form的左上角设置坐标系的起点?因为它设置了显示器左上角的起始点而不是形式,但我需要在Form的左上角开始点。
以下是我尝试做的代码:
int x, y;
string _x, _y;
private void GetCursor()
{
_x = MousePosition.X.ToString();
x = int.Parse(_x);
label2.Text = _x;
_y = MousePosition.Y.ToString();
y = int.Parse(_y);
label4.Text = _y;
}
private void MoveButton()
{
button1.Location = new Point(x,y);
}
private void timer1_Tick(object sender, EventArgs e)
{
GetCursor();
MoveButton();
}
感谢。
答案 0 :(得分:0)
您可以使用Control.PointToClient方法
Point localPoint = myForm.PointToClient(Cursor.Position);
label2.Text = localPoint.X.ToString();
label4.Text = localPoint.Y.ToString();
答案 1 :(得分:0)
首先添加类(Win32.cs)
public class Win32
{
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
}
}
然后从事件中调用它:
Win32.POINT p = new Win32.POINT();
p.x = Convert.ToInt16(txtMouseX.Text);
p.y = Convert.ToInt16(txtMouseY.Text);
Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);
txtMouseX
和txtMouseY
是自定义参数。我认为这应该在(0,0)。