How to get the position of a Click?

我只是一个虾纸丫 提交于 2019-11-26 23:14:19

问题


I'm currently making a game where the player will click on one of his units (which are pictureboxes) and a circle will become visible with the player's unit in the center. (Circle is also a picturebox) When the player clicks on the picturebox of the circle I need to figure out if the position of the click is inside the radius of the circle. My question is how do I get the position of the click?


回答1:


In click handler do:

   MousePosition.X
   MousePosition.Y

Add example:

        // 
        // pictureBox1 Init
        // 
        this.pictureBox1.Location = new System.Drawing.Point(1, 1);
        this.pictureBox1.Name = "pictureBox1";
        this.pictureBox1.Size = new System.Drawing.Size(100, 100);
        this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);

..........................................

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(string.Format("X: {0} Y: {1}", MousePosition.X, MousePosition.Y));
    }

Shows: "X: 537 Y: 946"

One more thing:

The MouseEventArgs with coordinates receive only MouseUp and MouseDown.

MouseClick can't recive you cordinates because click consists from MouseUp and MouseDown and it both can have different coordinates.

One more solution (Think it best)

    private int X;
    private int Y;

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(string.Format("X: {0} Y: {1}", X, Y));
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        X = e.X;
        Y = e.Y;
    }



回答2:


use the MouseClick event of the PictureBox for this sort of thing...

see
http://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mouseclick.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.mouseeventargs.aspx




回答3:


With Yahia's answer, I learned that the EventArgs can be cast to MouseEventArgs.

private void pictureBox1_Click(object sender, EventArgs e)
{
    MouseEventArgs e2 = (MouseEventArgs) e;
    MessageBox.Show(string.Format("X: {0} Y: {1}", e2.X, e2.Y));
}


来源:https://stackoverflow.com/questions/7055211/how-to-get-the-position-of-a-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!