27
Mar
09

[VB.Net] Q: How to get pixel colour

The question asked “On the image if i click anywhere, im supposed to tell the user what colour the pixel they clicked on was”

The solution:

Imports System.Runtime.InteropServices
Public Class Form1

    ''Required API DLL Imports
    <DllImport("gdi32.dll") >  Private Shared Function GetPixel(ByVal hdc As IntPtr, ByVal nXPos As Integer, ByVal nYPos As Integer) As Integer
    End Function
    <DllImport("gdi32.dll") >  Private Shared Function CreateDC(ByVal lpszDriver As String, ByVal lpszDevice As String, ByVal lpszOutput As String, ByVal lpInitData As IntPtr) As IntPtr
    End Function
    <DllImport("gdi32.dll") >  Private Shared Function DeleteDC(ByVal hdc As IntPtr) As Boolean
    End Function
    ''GetPixelColour Function
    Public Shared Function GetPixelColour(ByVal x As Integer, ByVal y As Integer) As Color
        Dim hdcScreen As IntPtr = _
            CreateDC("Display", Nothing, Nothing, IntPtr.Zero)
        Dim colorRef As Integer = GetPixel(hdcScreen, x, y)
        DeleteDC(hdcScreen)
        Return Color.FromArgb(colorRef And &HFF, (colorRef And &HFF00)  >  >  8, (colorRef And &HFF0000)  >  >  16)
    End Function

    Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
        Debug.WriteLine(GetPixelColour(Cursor.Position.X, Cursor.Position.Y))
    End Sub
End Class

Just add a picture box to the form, when you click on the picturebox it will write the colour to the debug output

Advertisements

0 Responses to “[VB.Net] Q: How to get pixel colour”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: