Skip to main content
 首页 » 编程设计

c#之相对于另一个表单 vb/c# 中的按钮移动 winform

2024年02月13日20qlqwjy

我想让你查看 this首先..

这就是我正在做的事情,按钮上的问题已解决,现在,无论何时何地拖动 map /图片,我都需要使 WinForm 跟随按钮。它是这样的,谷歌API上的infowindows。第一张图片,我用 html 制作的。

还有这个..这就是我现在正在做的,在 winForms 上,我不能用图片拖动 form2..

这是我当前的代码..

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    Dim loc As Point = PictureBox1.PointToClient(Button1.PointToScreen(Point.Empty)) 
    Button1.Parent = PictureBox1 
    Button1.Location = loc 
 
End Sub 
 
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Form2.Show() 
End Sub 
 
Private Sub pictureBox1_LocationChanged(ByVal sender As Object, ByVal e As EventArgs) 
 
    Dim p As Point = button1.PointToScreen(Point.Empty) 
    p.Offset(5, 10) 
    Form2.Location = p 
    Form2.Owner = Me 
End Sub 

如您所见,我希望那个信息窗口成为我的 winForms 中的一个表单。是否有可能它的位置可以像上面的链接一样是按钮的相对/父级。谢谢!

请您参考如下方法:

您可以尝试像这样处理图片框的 LocationChanged:

//LocationChanged event handler for your pictureBox1 
private void pictureBox1_LocationChanged(object sender, EventArgs e){ 
  //Get the location of button1 in screen coordinates 
  Point p = button1.PointToScreen(Point.Empty); 
  //Offset it to what you want 
  p.Offset(5,10); 
  //set the location for your infoWindow form 
  infoWindow.Location = p; 
} 

请注意,我使用 infoWindow 作为表单,我认为它在您的情况下可用,将 FormBorderStyle 设置为 None 并添加一些自定义关闭按钮...(您可以搜索更多相关信息,有大量示例)。如果您不知道如何注册 LocationChanged 事件处理程序,请看这里:

pictureBox1.LocationChanged += pictureBox1_LocationChanged; 

另请注意,您的 infoWindow 表单必须将您的主表单作为其所有者:

infoWindow.Owner = yourMainForm; 
//or this if the code is placed inside mainForm class 
infoWindow.Owner = this; 

更新:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
  Dim loc As Point = PictureBox1.PointToClient(Button1.PointToScreen(Point.Empty)) 
  Button1.Parent = PictureBox1 
  Button1.Location = loc 
  Form2.Owner = Me 
End Sub 
 
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
  Form2.Show() 
End Sub 
 
Private Sub pictureBox1_LocationChanged(ByVal sender As Object, ByVal e As EventArgs) Handles PictureBox1.LocationChanged 
 
  Dim p As Point = button1.PointToScreen(Point.Empty) 
  p.Offset(-Form2.Width/2, -Form2.Height-10) 
  Form2.Location = p 
 
End Sub