Find position of mouse relative to control, rather than screen

后端 未结 3 1417
醉话见心
醉话见心 2021-01-27 06:32

I have a Picture Box called BGImage. I hope that when the user clicks on this I can capture the position of the mouse relative to BGImage.

I\'v

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-27 07:20

    I have before the same problem and just solved with the help of some friends. Give a look Here mouse position is not correct Here its the code that give you the correct position of the Mouse Based On A Picture. Tanks to @Aaron he have give a final solution to this problem.

    This will put a red dot on the exact point you click. I wonder how useful setting the cursor position will be though, as they will almost certainly move the mouse after clicking the button (inadvertently or not).

    Setting the Cursor position needs to be in Screen coordinates - this converts back to client coordinates for drawing. I don't believe the PointToClient is necessary for the cursor position. In the below code, it is an unnecessary conversion, as you just go back to client coordinates. I left it in to show an example of each conversion, so that you can experiment with them.

    Public Class Form1
    Private PPoint As Point
    Public Sub New()
    
    ' This call is required by the designer.
    InitializeComponent()
    PictureBox1.BackColor = Color.White
    PictureBox1.BorderStyle = BorderStyle.Fixed3D
    AddHandler PictureBox1.MouseClick, AddressOf PictureBox1_MouseClick
    AddHandler Button8.Click, AddressOf Button8_Click
    ' Add any initialization after the InitializeComponent() call.
    
    End Sub
    
    Private Sub Button8_Click(sender As Object, e As EventArgs)
    Dim g As Graphics = PictureBox1.CreateGraphics()
    Dim rect As New Rectangle(PictureBox1.PointToClient(PPoint), New Size(1, 1))
    g.DrawRectangle(Pens.Red, rect)
    End Sub
    
    Private Sub PictureBox1_MouseClick(sender As Object, e As MouseEventArgs)
    PPoint = PictureBox1.PointToScreen(New Point(e.X, e.Y))
    Label8.Text = PPoint.X.ToString()
    Label9.Text = PPoint.Y.ToString()
    
    End Sub
    End Class
    

提交回复
热议问题