TAGS :Viewed: 7 - Published at: a few seconds ago

[ Writing Mouse Click X and Y to console ]

I am trying to write a program that needs to find the X and Y of a mouse click so I wrote this little Debug Code

Private Sub PictureBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseClick

  Console.WriteLine(ToString(e.X) + "," + ToString(e.Y))

End Sub

When I run it I get the error An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication1.exe I don't see how my code is wrong.

Answer 1

Nice VB.NET trap, induced by () meaning so many things. In this case, it is an indexing expression. You are actually calling the form's ToString() method, in other words Me.ToString() and that returns a string like "WindowsApplication1.Form1". Using (x) on a string is valid syntax, it returns the character at position x. Works when you keep the mouse in the far upper left corner, you get something like W,W :) But move the mouse and it goes Kaboom! when you index a position in the string that's beyond the string length.

Fix with:

 Console.WriteLine(e.X.ToString() + "," + e.Y.ToString())


 Console.WriteLine("{0},{1}", e.X, e.Y)



or the more sane:

 Label1.Text = e.Location.ToString()

Answer 2

Dose it compile? Change the line

Console.WriteLine(ToString(e.X) + "," + ToString(e.Y))


Console.WriteLine(e.X.ToString() + "," + e.Y.ToString())