Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

c# - How to get the position of a Click?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your click handler, do:

MousePosition.X
MousePosition.Y

Example:

// 
// pictureBox1 Init
// 
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 only receives MouseUp and MouseDown. A MouseClick can't receive your coordinates, because a click consists of a MouseUp and a MouseDown, and both can have different coordinates.

One more solution (I think this is 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...