GetPixel color from a picturebox

tripes

Member
Joined
Apr 16, 2009
Messages
18
Programming Experience
Beginner
i am working on a project in vb.net 2003 and i want to get the color of a pixel when i click on the image loaded in the picturebox. i ve tried anything but nothing seems to work.... help please:(:(
 
the code am using know

Private Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Int32, ByVal yPoint As Int32) As Int32

Private Declare Function GetPixel Lib "gdi32" Alias "GetPixel" (ByVal hdc As Int32, ByVal x As Int32, ByVal y As Int32) As Int32


Private Sub tmr_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmr.Tick

Dim win As Int32
Dim rgb As Int32
Dim hdc As Int32

win = WindowFromPoint(Windows.Forms.Cursor.Position.X, _
Windows.Forms.Cursor.Position.Y)

Dim g As Graphics = Graphics.FromHwnd(New IntPtr(win))

hdc = g.GetHdc.ToInt32

rgb = GetPixel(hdc, Windows.Forms.Cursor.Position.X, _
Windows.Forms.Cursor.Position.Y)

lblPic.BackColor = ColorTranslator.FromWin32(rgb)

txtHEX.Text = Hex(rgb).ToString
txtRGB.Text = rgb.ToString


End Sub


how can i modify this to get the pixel from the picturebox and not from the desktop?
 
See the thread I linked to again, in post 2 you will see a sample for the single line of code you need to accomplish this task.
 
ok i ve tried it and seems to work fine... but there is one problem, when i have the picture loaded to be streched so it can be the same size as picturebox, it does not work.... how can i fix this?
 
In that case it will only work if you stretch the image yourself prior to displaying in Picturebox. f.ex:
VB.NET:
Private Function StretchImage(ByVal img As Image, ByVal sz As Size) As Image
    Dim bmp As New Bitmap(sz.Width, sz.Height)
    Dim g As Graphics = Graphics.FromImage(bmp)
    g.DrawImage(img, New Rectangle(Point.Empty, sz), New Rectangle(Point.Empty, img.Size), GraphicsUnit.Pixel)
    g.Dispose()
    Return bmp
End Function
VB.NET:
Me.PictureBoxx.Image = Me.StretchImage(My.Resources.img, Me.PictureBoxx.ClientSize)
 
Back
Top