Here is the code:
Dim nBtn As New Button
PictureBox1.Controls.Add(nBtn)
nBtn.Text = "Click Me"
nBtn.Location = Cursor.Position ' or mouseposition = same result
that's how it looks.. its about 2 inches away from where I originally clicked it. My code doesn't even offset its location, so how is this happening?
That is a picture box inside the right side of SplitContainer
.
Control.Location
refers to the location relative to the control's container (or rather, its top-left point).
Cursor.Position
(and Control.MousePosition
) refer to a location relative to the top-left corner of the screen.
So if your control's container happens to be at the top-left of the screen, your code will work. Otherwise, it will be offset as you've seen. You should see whether the Control.PointToScreen
and Control.PointToClient
methods help you; the documentation isn't entirely clear to me, but they may be exactly what you need. For example:
nBtn.Location = PictureBox1.PointToClient(Cursor.Position)
See more on this question at Stackoverflow