Find position of mouse relative to control, rather than screen

后端 未结 3 1415
醉话见心
醉话见心 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
    
    0 讨论(0)
  • 2021-01-27 07:26

    Instead of using:

    Dim MousePos As Point = Me.PointToClient(MousePosition)
    

    You should be using:

    Dim MousePos As Point = BGImage.PointToClient(MousePosition)
    

    It will give you mouse position in BGImage coordinates, whereas the first code gives you the mouse position in the Form's coordinates.

    0 讨论(0)
  • 2021-01-27 07:29

    Add a mouse click event to your picture box
    Then use the MouseEventArgs to get the mouse position inside the picture box.
    This will give you the X and the Y location inside the picture box.

    Dim PPoint As Point
    Private Sub PictureBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseClick
        PPoint = New Point(e.X, e.Y)
        MsgBox(Convert.ToString(PPoint))
    End Sub
    
    0 讨论(0)
提交回复
热议问题