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

标签 c++ winforms opencv user-interface c++-cli

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

我的代码如下所示:

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

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

最佳答案

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

编辑 1:刚刚发现您已将 winform 标记为标签之一。如果您使用的是 winforms,则必须将 MouseHover 事件处理程序添加到您的 UI 控件。每当鼠标到达此区域时,都会调用此方法(https://learn.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 循环将再次导致您在问题中提出的相同问题。

关于c++ - 将鼠标悬停在图片框上时,如何显示带有 x-y 坐标的十字线光标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52083910/

相关文章:

c# - .NET 数据绑定(bind)的跨线程问题

.net - 可用文化列表

python-3.x - 如何在Python中使用欧式距离进行人脸识别

python - OpenCV 3.0 的 Homebrew 程序安装未链接到 Python

python - 如何使图像看起来更均匀而不丢失精细细节

C++ - 构造函数和自引用类

c++ - 可变函数包装器

c++ - #用空格定义

c++ - C++11 中的 sequenced-before 关系是否会阻止编译器/CPU 重新排序?

c# - 为游戏创建控制分配器菜单