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

How could I display a crosshair cursor with x-y coordinates when hovering over a picturebox?

本文关键字:坐标 x-y 光标 十字 悬停 鼠标 何显示 显示      更新时间:2023-10-16

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

我的代码如下所示:

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:刚刚发现您已将wform标记为标签之一。如果您使用的是 winforms,则必须将鼠标悬停事件处理程序添加到 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 循环将再次导致您在问题中提出的相同问题。