简体   繁体   中英

C#, How to set the cursor position manually

I did the "Get Coordinates" part and I need to do the "Set" part, where I can enter the coordinates manually and press "Set" button to make the "Blue Cirlce" to be appeared with the coordinates that I have entered in textBox2 on pictureBox1 . This code for is "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);
    }

表格

add the button click event processing method 'ButtonSet_Click' to the 'set' button.

    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;
    }

If I understand correctly, you are trying to find a way to parse your input into coordinates. Try this (you need to carefully validate the input string and handle the potential exception thrown when casting string to 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM