Вопрос

In the previous question:

After button was pressed, get pixel properties from a picturebox only after mouse was clicked c#

@ArturUdod gave me this answer:

public Form1()
{
    InitializeComponent();
    this.myPictureBox.BackColor = Color.Red;
}

private void startButton_Click(object sender, EventArgs e)
{
    if (MessageBox.Show(
        "Please click the object in the image ",
        "", 
        MessageBoxButtons.OKCancel, 
        MessageBoxIcon.Exclamation, 
        MessageBoxDefaultButton.Button1) == DialogResult.OK)
    {
        this.myPictureBox.MouseClick += this.myPictureBox_MouseClick;
    }
}

void myPictureBox_MouseClick(object sender, MouseEventArgs e)
{
    this.myPictureBox.MouseClick -= myPictureBox_MouseClick;
    var point = new Point(e.X, e.Y);
    MessageBox.Show(string.Format("You've selected a pixel with coordinates: {0}:{1}", point.X, point.Y));
}

For the following scenario : 1) user presses some button 2) message box appears 3) user clicks OK button 4) messagebox dissappears 5) user clicks the image 6) you start processing something.

But right now I need the following scenario : 1) user presses a button 2) message box appears 3) user clicks OK button 4) messagebox dissappears 5) user clicks the image 6) the program recors clicked pixel's coordinates 7) messagebox appears 8) user clicks OK 9) messagebox dissappears 10) user click the image again 11) the program recors clicked pixel's coordinates 12)the image processing starts based on the two coordinates

The method above doesn't work for my new scenario, and I don't know how to adapt it. I also need to use the same picturebox.

Thanx!

Это было полезно?

Решение

You need 2 variables for the clicked Points, just make a counter and you've done:

int i = 0;
Point p1, p2;
void myPictureBox_MouseClick(object sender, MouseEventArgs e) {
  if(i == 1) this.myPictureBox.MouseClick -= myPictureBox_MouseClick;
  var point = new Point(e.X, e.Y);
  MessageBox.Show(string.Format("You've selected a pixel with coordinates: {0}:{1}", point.X, point.Y));
  if(i == 0) p1 = point;
  else p2 = point;
  i++;
}
//then use the two points p1,p2 for further processing.

Note that, if you want to implement in your way (using -= to unregister the handler and so disable clicking on the PictureBox), you should notice to disable the Start button right after clicking it and enable it back at property time like this:

private void startButton_Click(object sender, EventArgs e) {
   //all the code you already had go first...
   startButton.Enabled = false;
}
void myPictureBox_MouseClick(object sender, MouseEventArgs e) {
   //...
   if(i == 0) p1 = point;
   else { 
      p2 = point;
      startButton.Enabled = true;
   }
   i++;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top