5 ответов:
A c# version: Как получить цвет пикселя на X,Y с помощью c# ?
Должно быть легко переписать в VB.NET.
Быстрый простой очень медленный, но он работает.
Идея состоит в том, чтобы скопировать экран в растровое изображение, которое можно сделать с помощью GDI+ build в чертеж.графический объект. Затем просто прочитайте растровое изображение, которое он генерирует. Получить пиксель очень медленно. Лучший способ-это читать байтовый массив изображения напрямую.
Function MakeScreenShot() As Drawing.Bitmap Dim out As Drawing.Bitmap 'Get the screen Size Dim bounds As Rectangle = Screen.GetBounds(Point.Empty) 'create the bitmap out = New Drawing.Bitmap(bounds.Width, bounds.Height) 'create a graphic object to recive the pic Using gr As Drawing.Graphics = Graphics.FromImage(out) 'Copy the screen using built in API gr.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size) End Using Return out End Function Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click Dim BM As Drawing.Bitmap = MakeScreenShot() Dim mouseloc As Point = Cursor.Position Dim c As Color = BM.GetPixel(mouseloc.X, mouseloc.Y) ' The Slowest way possable to read a color Debug.Print(c.R & "," & c.G & "," & c.B) End SubНаслаждайтесь.
Попробуйте этот код:
#Region "#include" Imports System Imports System.Drawing Imports System.Runtime.InteropServices #End Region Public Class Test #Region "From Windows API" <DllImport("user32.dll", SetLastError:=True)> _ Public Shared Function GetWindowDC(ByVal hwnd As IntPtr) As IntPtr 'Do not try to name this method "GetDC" it will say that user32 doesnt have GetDC !!! End Function <DllImport("user32.dll", SetLastError:=True)> _ Public Shared Function ReleaseDC(ByVal hwnd As IntPtr, ByVal hdc As IntPtr) As Int32 End Function <DllImport("gdi32.dll", SetLastError:=True)> _ Public Shared Function GetPixel(ByVal hdc As IntPtr, ByVal nXPos As Integer, ByVal nYPos As Integer) As UInteger End Function #End Region REM --Test-- #Region "Some Functions" Public Function GetPixelColor(ByVal x As Integer, ByVal y As Integer) As Color Dim hdc As IntPtr = GetWindowDC(IntPtr.Zero) Dim pixel As UInteger = GetPixel(hdc, x, y) Dim color As Color ReleaseDC(IntPtr.Zero, hdc) MsgBox(pixel) color = color.FromArgb(Int(pixel And &HFF), _ Int(pixel And &HFF00) >> 8, _ Int(pixel And &HFF0000) >> 16) Return color End Function #End Region REM --Test-- #Region "OnClick" Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim mouseloc As Point = Cursor.Position Me.Label1.BackColor = GetPixelColor(mouseloc.X, mouseloc.Y) Me.Refresh() End Sub #End Region End ClassВам нужна кнопка (name= = Button1) и метка (name==Label1). Чтобы получить цвет с экрана, вам нужно будет использовать таймер.
Если вам нужно переписать код с C# на VB.NET используйте эту ссылку: http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
Держите его простым, не очень оптимизированным, но выполняйте работу:
Public Class Form1 Declare Auto Function FindWindow Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr Declare Function GetDC Lib "user32" (ByVal hWnd As IntPtr) As IntPtr Declare Function ReleaseDC Lib "user32" (ByVal hwnd As IntPtr, ByVal hdc As IntPtr) As IntPtr Private Declare Function GetPixel Lib "gdi32" (ByVal hdc As IntPtr, ByVal X As Int32, ByVal Y As Int32) As Int32 Private Function CheckScreen() Dim CursorLoc As Point = Cursor.Position Dim hDC As IntPtr = GetDC(0) '0 = Get the color to any window on screen, not only your app Try Dim CursorColor As Integer = GetPixel(hDC, CursorLoc.X, CursorLoc.Y) Me.Panel1.BackColor = ColorTranslator.FromWin32(CursorColor) 'a simple panel to show the color Me.Refresh() Return True Catch ex As Exception Return False Finally ReleaseDC(0, hDC) End Try End Function Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Me.Timer1.Start() 'Timer with a short delay End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick CheckScreen() End Sub End Class
Это на самом деле сложнее, чем вы думаете. Я бы искал какой-нибудь пример кода, который уже делает это, и копировал их технику.
В конце концов, алгоритм должен будет выполнить следующие операции:
- получить растровое изображение рабочего стола / окна рядом с позицией курсора
- индексируйте это растровое изображение с помощью позиции курсора и извлеките цвет пикселя
Это звучит просто, но не так просто.
Comments