C#,如何手动设置光标位置

时间:2018-05-20 08:58:57

标签: c# winforms cursor coordinates

我做了#34;获得坐标"部分我需要做" Set"部分,我可以手动输入坐标,然后按"设置"按钮制作" Blue Cirlce"与textBox2 pictureBox1上输入的坐标一起显示。 此代码为" Get":

    int mouseX, mouseY;
    Pen bluePen = new Pen(Color.Blue, 1);
    private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
    {
        textBox1.Text = "X = " + e.X + " ; Y = " + e.Y;
    }
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        mouseX = e.X;
        mouseY = e.Y;
        pictureBox1.Refresh();
    }
    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle circle = new Rectangle(mouseX - 8, mouseY - 8, 16, 16);
        e.Graphics.DrawEllipse(bluePen, circle);
    }

The form

2 个答案:

答案 0 :(得分:1)

添加按钮点击事件处理方法' ButtonSet_Click'到了#set;'按钮。

    private void ButtonSet_Click(object sender, EventArgs e)
    {                    
        Point p = getXYfromTextBox();
        Rectangle circle = new Rectangle(p.X - 8, p.Y - 8, 16, 16);
        Graphics g = pictureBox1.CreateGraphics();
        g.DrawEllipse(redPen, circle);
    }

    //this method can be optimized
    private Point getXYfromTextBox()
    {
        string xy = textBox2.Text.Trim();
        string[] xys = xy.Split(';');
        mouseX = Convert.ToInt32(xys[0].Split('=')[1].Trim());
        mouseY = Convert.ToInt32(xys[1].Split('=')[1].Trim());
        Point p = new Point(mouseX, mouseY);
        return p;
    }

答案 1 :(得分:0)

如果我理解正确,您正试图找到一种方法来将您的输入解析为坐标。试试这个(你需要仔细验证输入字符串并处理将字符串转换为int时抛出的潜在异常。)

private void btnSet_Click(object sender, EventArgs e)
{
    string input = tbInput.Text.Trim(); 
    string[] parts = input.Split(",".ToCharArray()); //assume your coordinates are commas-separated, like "80,100"
    if (parts.Length == 2)
    {
        mouseX = int.Parse(parts[0]);
        mouseY = int.Parse(parts[1]);
        pictureBox1.Refresh(); //Now force picturebox to repaint
    }
}