将鼠标悬停在图片框上时,如何显示带有x-y坐标的十字光标?

问题描述 投票:0回答:1

我想在悬停在图片框上时制作十字准线指针,并在图片框上按下鼠标左键时存储坐标。

我的代码如下所示:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
        cv::VideoCapture cap;
        cap.open(0);

        if (!cap.isOpened()) {
            MessageBox::Show("Failed To Open WebCam");
            _getch();
            return;
        }

        ///query_maximum_resolution(cap, pictureBox1->Width, pictureBox1->Height);
        cap.set(CV_CAP_PROP_FRAME_WIDTH, pictureBox1->Width);
        cap.set(CV_CAP_PROP_FRAME_HEIGHT, pictureBox1->Height);

        Pen^ myPen = gcnew Pen(Brushes::Red);

        while (1)
        {
            cap.read(frame);

            pictureBox1->Image = mat2bmp.Mat2Bimap(frame);
            Graphics^ g = Graphics::FromImage(pictureBox1->Image);
            Point pos = this->PointToClient(System::Windows::Forms::Cursor::Position);
            g->DrawLine(myPen, pos.X, 0, pos.X, pictureBox1->Height);
            g->DrawLine(myPen, 0, pos.Y, pictureBox1->Width, pos.Y);
            pictureBox1->Refresh();
            delete g;
        }
    }

但是当我运行代码时,它会变得更慢而且没有响应。任何想法,使其快速和有效。任何帮助都会有所帮助。

c++ winforms opencv user-interface c++-cli
1个回答
2
投票

IO发生在UI线程上,这是主要的应用程序UI呈现线程。按钮单击是一个事件处理程序,将出现在UI线程上。如果在UI线程中运行了while循环,它将使应用程序挂起。在UI线程上完成的工作应该很小或异步。

编辑1:刚刚发现您已将winform标记为其中一个标记。如果您使用的是winforms,则必须向UI控件添加MouseHover事件处理程序。只要鼠标到达此区域,就会调用此方法(https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.mousehover?view=netframework-4.7.2)。在这个方法中,只需编写上面的代码而不使用while循环。像这样的东西。

private: System::Void button1_MouseHover(System::Object^  sender, System::EventArgs^  e) {
    cv::VideoCapture cap;
    cap.open(0);

    if (!cap.isOpened()) {
        MessageBox::Show("Failed To Open WebCam");
        _getch();
        return;
    }

    ///query_maximum_resolution(cap, pictureBox1->Width, pictureBox1->Height);
    cap.set(CV_CAP_PROP_FRAME_WIDTH, pictureBox1->Width);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, pictureBox1->Height);

    Pen^ myPen = gcnew Pen(Brushes::Red);

    cap.read(frame);

    pictureBox1->Image = mat2bmp.Mat2Bimap(frame);
    Graphics^ g = Graphics::FromImage(pictureBox1->Image);
    Point pos = this->PointToClient(System::Windows::Forms::Cursor::Position);
    g->DrawLine(myPen, pos.X, 0, pos.X, pictureBox1->Height);
    g->DrawLine(myPen, 0, pos.Y, pictureBox1->Width, pos.Y);
    pictureBox1->Refresh();
    delete g;
}

注意:此事件也出现在UI线程中。每次鼠标在感兴趣的区域都会出现这种情况。因此,您不需要while循环。在此处添加while循环将再次导致您在问题中提出的相同问题。

© www.soinside.com 2019 - 2024. All rights reserved.