How to get the position of a Click?

后端 未结 3 574
终归单人心
终归单人心 2020-12-06 04:51

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.

相关标签:
3条回答
  • 2020-12-06 05:28

    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

    0 讨论(0)
  • 2020-12-06 05:29

    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));
    }
    
    0 讨论(0)
  • 2020-12-06 05:34

    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;
    }
    
    0 讨论(0)
提交回复
热议问题