简体   繁体   English

如何获取Windows窗体应用程序中发件人的位置(坐标)?

[英]How to get the senders' position (coordinates) in Windows Form Application?

I just began learning WinForms and am currently baffled on how to get the senders' (mouses') position (coordinates). 我刚刚开始学习WinForms ,目前对如何获取发件人 (鼠标)位置(坐标)感到困惑。 I tried searching but to no avail. 我尝试搜索,但无济于事。

This is my, somewhat, of a try but, sadly, it ended up with an error: 这是我的尝试,但不幸的是,它最终出现错误:

private: System::Void pictureBox1_MouseHover(System::Object^  sender, System::EventArgs^  e) {
    this->pictureBox1->Location = System::Drawing::Point(sender::Position.X - 5, sender::Position.Y - 5);
    MessageBox::Show("Foo", "Bar", MessageBoxButtons::OK, MessageBoxIcon::Stop);
}

So my question here is quite clear, I think: how can I get the senders' position (in this case, the mouses'). 因此,我认为我的问题很清楚:我如何获得发件人的位置(在本例中为鼠标的位置)。 Explanations would also be of help. 解释也将有所帮助。 Thank you. 谢谢。

Since I didn't find a valid answer I took the longer route. 由于找不到有效答案,因此我选择了更长的路线。

Firstly, I declared a boolean in the namespace with the value of false (it will change to true when the mouse will touch the picture). 首先,我在namespace声明了一个boolean值,其值为false (当鼠标触摸图片时,它将变为true)。 Then I create two new methods: one to get the X and Y of the mouse and execute code if the mouse is touching the picture and the second one to determine whether the mouse is touching the picture or not. 然后,我创建了两种新方法:一种用于获取鼠标的XY并在鼠标触摸图片时执行代码,另一种用于确定鼠标是否在触摸图片。

private: System::Void picture_MouseMove(Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
    int VMouseX = e->X,
        VMouseY = e->Y;
    if (VMouseEntered) {
        VMouseEntered = false;
        this->picture->Location = System::Drawing::Point(VMouseX + 17, VMouseY + 17);
    }
}

private: System::Void picture_MouseEnter(System::Object^ sender, System::EventArgs^ e) {
    VMouseEntered = true;
}

Then, I create two new EventHandlers for the picture. 然后,我为图片创建两个新的EventHandlers The first EventHandler is to listen for mouse movement, the second one is to check whether the mouse is touching the picture. 第一个EventHandler用于侦听鼠标的移动,第二个EventHandler用于检查鼠标是否在触摸图片。

this->picture->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::picture_MouseMove); // Checks for mouse movement.
this->picture->MouseEnter += gcnew System::EventHandler(this, &Form1::picture_MouseEnter); // Checks whether the mouse is touching the picture.

Done. 做完了 I hope that this will help someone. 我希望这会对某人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM