在对象计时器内,DrawnObject不会随鼠标移动

时间:2014-03-06 22:36:09

标签: vb.net winforms

我有一个项目尝试使用计时器在一个图片框中使用鼠标左右移动鼠标。还需要考虑我移动鼠标的速度有多快。我尝试在下面做这个代码,我的矩形不会移动?为什么呢?

Dim p as rectangle

Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles PictureBox1.Paint
  Dim g As System.Drawing.Graphics
  g = e.Graphics

  Dim PaddleSize As New Size(50, 10)
  Dim MystartingPoint As New Point(225, PictureBox1.Height - 50)
  p = New Rectangle(MystartingPoint, PaddleSize)
  g.FillRectangle(Brushes.OliveDrab, p)       
End Sub

Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
  p.Location = Me.PointToClient(New Point(MousePosition.X - 25, PictureBox1.Height - 50))
  pictureBox1.refresh()    
End Sub

1 个答案:

答案 0 :(得分:0)

您的起点永远不会改变(它总是在225 x高度 - 50),因为您忽略了tick事件中的信息。

我的猜测是你试图用鼠标移动在屏幕上来回移动,所以尝试这样的事情:

Private p As Point

Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) _
  Handles PictureBox1.Paint
  e.Graphics.FillRectangle(Brushes.OliveDrab, New Rectangle(p, New Size(50, 10)))
End Sub

Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) _
  Handles Timer1.Tick
  p = New Point(PictureBox1.PointToClient(New Point(MousePosition.X - 25, 0)).X,
                PictureBox1.Height - 50)
  PictureBox1.Refresh()
End Sub

您不希望在PointToClient计算中包含PictureBox.Height - 50,因为您确实希望paddle始终与控件底部相距50像素。