按下按钮后,只有在单击鼠标后才能从图片框中获取像素属性c#

时间:2013-12-01 11:25:59

标签: c# events click mouseevent picturebox

我有以下代码:

    private void Calculate_Click(object sender, EventArgs e)
    {
        if (MessageBox.Show("Please click the object in the image ", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) == DialogResult.OK)
        {
            click_the_object();
        }
    }

在click_the_object()函数中,我想点击图片框中的一个像素并获得它的颜色。

获取像素属性的函数是:

    private Color culoarepixel(Point point)
    {
        Bitmap bitmap = (Bitmap)pbOriginal.Image;

        return bitmap.GetPixel(point.X, point.Y);
    }

问题是我不知道如何使click_the_object()函数记录只有一次点击,第一次点击。我尝试使用eventhandler,但它进入循环。

1 个答案:

答案 0 :(得分:2)

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