• 如何由滑鼠游標取得顏色值

說明

    因為VB內建的point 只限取得該Form的座標點 如果要取得螢幕上任意點的顏色該如何做呢

    這可以使用GetPixel取得某個座標的顏色 他的宣告如下
    Private Declare Function GetPixel Lib "gdi32" (ByVal hDC As Long, ByVal x As Long, ByVal y As Long) As Long
    首先必須傳入目標的hDC 以及座標

  方法一

    如何由滑鼠座標取得視窗的hWnd可以由滑鼠游標取得hWnd 只要再透過GetWindowDC即可取得視窗的hDC

    而座標是相對於目標視窗 而不是相對於螢幕 所以首先先用GetWindowRect
    取得視窗的範圍 然後相減就可以得到相對座標然後只要將這相直傳到GetPixel就可以了 取得方法如下

      GetCursorPos lpPoint '取得滑鼠座標
      GetWindowRect hWnd, lpRect '取得視窗的範圍
      x = lpPoint.x - lpRect.Left '這是相對於視窗的x座標
      y = lpPoint.y - lpRect.Top '這是相對於視窗的y座標

    完整的程式如下

程式

    '這個程式需要一個Timer,一個Picture1
    Option Explicit

    Private Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, ByVal yPoint As Long) As Long
    Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
    Private Declare Function GetWindowDC Lib "user32" (ByVal hWnd As Long) As Long
    Private Declare Function GetPixel Lib "gdi32" (ByVal hDC As Long, ByVal x As Long, ByVal y As Long) As Long
    Private Declare Function GetWindowRect Lib "user32" (ByVal hWnd As Long, lpRect As RECT) As Long

    Private Type RECT
            Left As Long
            Top As Long
            Right As Long
            Bottom As Long
    End Type

    Private Type POINTAPI
        x As Long
        y As Long
    End Type

    Private Sub Form_Load()
    Timer1.Interval = 5
    Timer1.Enabled = True
    End Sub

    Private Sub Timer1_Timer()
    Dim hWnd As Long, hDC As Long, x As Long, y As Long
    Dim lpPoint As POINTAPI, lpRect As RECT

    GetCursorPos lpPoint '取得滑鼠座標
    hWnd = WindowFromPoint(lpPoint.x, lpPoint.y) '由回屬座標取得視窗的hWnd
    GetWindowRect hWnd, lpRect '取得視窗的範圍
    x = lpPoint.x - lpRect.Left '這是相對於視窗的x座標
    y = lpPoint.y - lpRect.Top '這是相對於視窗的y座標

    '取得視窗的hDC
    hDC = GetWindowDC(hWnd)

    '取得顏色並顯示
    Picture1.BackColor = GetPixel(hDC, x, y)
    End Sub

  方法二

    有個更簡易的方式 只要取得桌面的hDC直接傳入就可以了 可以參考以下完整的程式

程式

    '這個程式需要一個Timer,一個Picture1
    Option Explicit

    Private Declare Function GetPixel Lib "gdi32" (ByVal hDC As Long, ByVal x As Long, ByVal y As Long) As Long

    Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long

    Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long


    Private Type POINTAPI
        x As Long
        y As Long
    End Type

    Private Sub Form_Load()
    Timer1.Interval = 5
    Timer1.Enabled = True
    End Sub

    Private Sub Timer1_Timer()
    Dim hDC As Long
    Dim lpPoint As POINTAPI

    GetCursorPos lpPoint '取得滑鼠座標

    '取得桌面的hDC
    hDC = GeDC(0)

    '取得顏色並顯示
    Picture1.BackColor = GetPixel(hDC, lpPoint.x, lpPoint.y)
    End Sub

文件出處

    Honey

整理時間

    2002,3,30

VB心得筆記歡迎各位的指教,如果您有任何文章或資料願意提供給我們的,請來信到VBNote

如果對本站有任何建議,歡迎來信給Honey,我們會盡快給您答覆