Jump to content

ScreenColorPicker snap color from screen with the mouse pointer


Recommended Posts

ScreenColorPicker  snap color from screen with the mouse pointer to clipboard

:idea:  the idea comes from @Melba23's Magnify  post. Thanks for that!            image.png.f4e96493f19d6e1c194ebcfe3e492a7d.png      

;https://www.autoitscript.com/forum/topic/209412-screencolorpicker-snap-color-from-screen-with-the-mouse-pointer/

#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7
;ScreenColorPicker.au3
;snap color from screen with the mouse pointer
#NoTrayIcon
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <StaticConstants.au3>
#include <WinAPI.au3>
#include <Misc.au3>
#include <StringConstants.au3>
#include <TrayConstants.au3>

; to avoid running it multiple times!
If _Singleton(@ScriptName, 1) = 0 Then Exit

Opt("TrayMenuMode", 3) ; These are options 1 and 2 for TrayMenuMode.

Global $hMag_GUI, $hMagDC, $hDeskDC, $hPen, $oObj, $aMouse_Pos[2], $iLast_Mouse_X = 0, $iLast_Mouse_Y = 0
Local $mColor, $hColor_Win, $ColorLabel, $ColorRec

TraySetIcon(StringLeft(@AutoItExe, StringInStr(@AutoItExe, "\", $STR_NOCASESENSEBASIC, -1) - 1) & "\Icons\MyAutoIt3_Red.ico")
TraySetToolTip("ColorPicker")

#Region === Tray_Menu ===
;~ Local $idPaused = TrayCreateItem("Pause", -1, -1, $TRAY_ITEM_RADIO)
;~ TrayItemSetState(-1, $TRAY_UNCHECKED)
Local $TrayColorPicker = TrayCreateItem("ColorPicker")
Local $TrayHelp = TrayCreateItem("Help")
TrayCreateItem("") ; Create a separator line.
Local $TrayExit = TrayCreateItem("Exit")
#EndRegion === Tray_Menu ===

Local $hDLL = DllOpen("user32.dll")

While 1
    Switch TrayGetMsg()
        Case $TRAY_EVENT_PRIMARYDOUBLE ;* ColorPicker
            ColorPicker()

        Case $TrayColorPicker ; ColorPicker
            ColorPicker()

        Case $TrayHelp ; Help
            HelpInfo()

        Case $TrayExit ; Exit
            GoToExit()

    EndSwitch

    ;if END key close ColorPicker
    If _IsPressed("23", $hDLL) Then
        Sleep(300)
        ColorPicker()
    EndIf

    Sleep(50)
WEnd

GoToExit()
;----------------------------------------------------------------------------------------
Func GoToExit()    ; exit
    CloseColorPicker()
    DllClose($hDLL)
    Exit
EndFunc   ;==>GoToExit
;----------------------------------------------------------------------------------------
Func ColorPicker()

    ; Create Color GUI
    $hColor_Win = GUICreate("Color", 100, 30, 0, 0, $WS_POPUP, BitOR($WS_EX_TOOLWINDOW, $WS_EX_TOPMOST))
    GUICtrlCreateLabel("Label1", 0, 0, 100, 30, $SS_BLACKFRAME)
    $ColorLabel = GUICtrlCreateLabel(" ", 26, 7, 74, 20)
    $ColorRec = GUICtrlCreateLabel(" ", 1, 1, 25, 28)
    GUICtrlSetFont($ColorLabel, 10, 600, 0, "Consolas")
    GUICtrlSetBkColor($ColorLabel, $GUI_BKCOLOR_TRANSPARENT)
    GUISetState(@SW_SHOW, $hColor_Win)

    ; Create MAG GUI
    $hMag_GUI = GUICreate("MAG", 100, 100, 0, 0, $WS_POPUP, BitOR($WS_EX_TOOLWINDOW, $WS_EX_TOPMOST))
    GUISetState(@SW_SHOW, $hMag_GUI)

    ; Get device context for Mag GUI
    $hMagDC = _WinAPI_GetDC($hMag_GUI)
    If @error Then Exit
    ; Get device context for desktop
    $hDeskDC = _WinAPI_GetDC(0)
    If @error Then
        _WinAPI_ReleaseDC($hMag_GUI, $hMagDC)
        Exit
    EndIf

    ; Create pen
    $hPen = _WinAPI_CreatePen($PS_SOLID, 5, 0x7E7E7E)
    $oObj = _WinAPI_SelectObject($hMagDC, $hPen)

    While 1

        ; Check if cursor has moved
        $aMouse_Pos = MouseGetPos()
        If $aMouse_Pos[0] <> $iLast_Mouse_X Or $aMouse_Pos[1] <> $iLast_Mouse_Y Then
            ; Redraw Mag GUI
            Loupe($aMouse_Pos)
            ; Reset position
            $iLast_Mouse_X = $aMouse_Pos[0]
            $iLast_Mouse_Y = $aMouse_Pos[1]
        EndIf

        Select
            Case _IsPressed("02", $hDLL) Or _IsPressed("10", $hDLL) ; 02 = Right mouse button ; 10 = SHIFT key
                TakeSnap()
                Return

            Case _IsPressed("23", $hDLL) ;23 END key
                TakeSnap()
                Return

            Case _IsPressed("1B", $hDLL) ;1B = ESC key
                CloseColorPicker()
                Return

            Case _IsPressed("25", $hDLL) ; 25 = LEFT ARROW key
                MouseMove($aMouse_Pos[0] - 1, $aMouse_Pos[1])
                Sleep(100)

            Case _IsPressed("26", $hDLL) ; 26 = UP ARROW key
                MouseMove($aMouse_Pos[0], $aMouse_Pos[1] - 1)
                Sleep(100)

            Case _IsPressed("27", $hDLL) ; 27 = RIGHT ARROW key
                MouseMove($aMouse_Pos[0] + 1, $aMouse_Pos[1])
                Sleep(100)

            Case _IsPressed("28", $hDLL) ; 28 = DOWN ARROW key
                MouseMove($aMouse_Pos[0], $aMouse_Pos[1] + 1)
                Sleep(100)

        EndSelect

    WEnd

EndFunc   ;==>ColorPicker
;----------------------------------------------------------------------------------------
Func Loupe($aMouse_Pos)
    Local $iX, $iY

    ; Fill Mag GUI with 10x expanded contents of desktop area (5 pixels around mouse)
    DllCall("gdi32.dll", "int", "StretchBlt", _
            "int", $hMagDC, "int", 0, "int", 0, "int", 100, "int", 100, _
            "int", $hDeskDC, "int", $aMouse_Pos[0] - 5, "int", $aMouse_Pos[1] - 5, "int", 10, "int", 10, _
            "long", $SRCCOPY)

    ; Original 10 x 10 expanded to 100 x 100 - 10x magnification

    $mColor = PixelGetColor($aMouse_Pos[0], $aMouse_Pos[1])
    $mColor = "0x" & Hex($mColor, 6) ;  * <--------------  color converted to hexadecimal
    GUICtrlSetData($ColorLabel, $mColor)
    GUICtrlSetBkColor($ColorRec, $mColor)

    ; Keep Mag GUI on screen
    If $aMouse_Pos[0] < (@DesktopWidth - 120) Then
        $iX = $aMouse_Pos[0] + 20
    Else
        $iX = $aMouse_Pos[0] - 120
    EndIf
    If $aMouse_Pos[1] < (@DesktopHeight - 150) Then
        $iY = $aMouse_Pos[1] + 20
    Else
        $iY = $aMouse_Pos[1] - 120
    EndIf
    WinMove($hMag_GUI, "", $iX, $iY, 100, 100)
    WinMove($hColor_Win, "", $iX, $iY + 100)

EndFunc   ;==>Loupe
;----------------------------------------------------------------------------------------
Func TakeSnap()
    ClipPut($mColor)
    ConsoleWrite($mColor & @CRLF)
    WinMove($hColor_Win, "", @DesktopWidth - 120, @DesktopHeight - 75)
    GUISetState(@SW_HIDE, $hMag_GUI)
    WinWait("[CLASS:#32768]", "", 1)
    If WinExists("[CLASS:#32768]") Then Send("{ESC}")
    Sleep(3000)
    CloseColorPicker()
EndFunc   ;==>TakeSnap
;----------------------------------------------------------------------------------------
Func CloseColorPicker()
    ; Clear up Mag GUI
    _WinAPI_SelectObject($hMagDC, $oObj)
    _WinAPI_DeleteObject($hPen)
    _WinAPI_ReleaseDC(0, $hDeskDC)
    _WinAPI_ReleaseDC($hMag_GUI, $hMagDC)
    GUIDelete($hMag_GUI)
    GUIDelete($hColor_Win)
EndFunc   ;==>CloseColorPicker
;----------------------------------------------------------------------------------------
Func HelpInfo()

    Local $Msg = @CRLF & "HotKey {END} call ColorPicker." & @CRLF & @CRLF _
             & "During ColorPicker is active" & @CRLF & @CRLF _
             & "{END} or {SHIFT} or Right mouse button" & @TAB & @CRLF _
             & "snap the Color to clipboard " & @CRLF & @CRLF _
             & "{LEFT}, {UP}, {RIGHT}, {DOWN}" & @CRLF _
             & "moves the mouse by 1 pixel" & @CRLF & @CRLF _
             & "{ESC} close ColorPicker to tray" & @CRLF & @CRLF _
             & "--->  Press {ESC} to exit  <---  " & @CRLF _
             & " " & @CRLF

    ToolTip($Msg, @DesktopWidth / 2, @DesktopHeight / 5, "info", 1)
    GUICtrlSetFont(-1, 14, 600, 0, "Arial")

    Do
        Sleep(100)
    Until _IsPressed("1B", $hDLL) ; 1B ESC key

    ToolTip("")

EndFunc   ;==>HelpInfo

 

Please, leave your suggestion , comments , experiences here. 

Thank you!  :)

 

Edited by ioa747
Link to post
Share on other sites

Hi @ioa747,

what I like is the Loupe() and the general idea 👍 . What I don't like or at least just do not understand is, the HotKeySet("{END}", "ColorPicker") on line 35. Each time I press end, the picker image is freezed. Is this intended and if yes, why and for what?

image.thumb.png.84350815fd595e4972b64f36b09acf05.png

Besides that, good job 😀 . As I small suggestion regarding code improvement, I would say you could restructure your code a bit more.

Best regards
Sven

________________
Stay innovative!

Stay innovative!

Spoiler

🌍 Au3Forums

📊 AutoIt limits/defaults

💎 Code Katas: [...] (comming soon)

🎭 Collection of GitHub users with AutoIt projects

🐞 False-Positives

🔍 Forum search

🔮 Me on GitHub

💬 Opinion about new forum sub category

 📑 UDF wiki list

✂ VSCode-AutoItSnippets

📑 WebDriver FAQs

👨‍🏫 WebDriver Tutorial (coming soon)

Link to post
Share on other sites
5 hours ago, SOLVE-SMART said:

What I don't like or at least just do not understand is, the HotKeySet("{END}", "ColorPicker") on line 35.

:oops:  You have right !!

With HotKeySet the script flow was trapped in loop.

I replace the code.   Thank you very much for response and your suggestion!  :)

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Trax
      This is kind of a side question but it has always driven me a little crazy. A vast majority of times (as in the example below) I have windows that really only contain one value at any given time. I never want to scroll. I never want lists. if I put a value in that windows I want it to overwrite the value that is already there. After looking at all the options I have chosen a listbox. Is that really my best option?
         Anyway..... I have been trying to get things to display in color and am having fits. It might somehow relate to the above side question. I have been using Melba23's example here:
      and can't get anything to display in the windows.  Here is my code:
       
      <#region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Icon=SRT.ico #AutoIt3Wrapper_Res_Comment= #AutoIt3Wrapper_Res_Description= #AutoIt3Wrapper_Run_Au3Stripper=n #Au3Stripper_Parameters=/so #endregion ;**** Directives created by AutoIt3Wrapper_GUI **** AutoItSetOption("MouseCoordMode", 1) ; 0=Relative to Active Window, 1=Absolute Screen 2=Relitive to Client Area AutoItSetOption("GUICloseOnESC", 1) ; Close on ESC #include-once Opt("TrayMenuMode", 1) #include <GUIConstantsEx.au3> #include <GUIListBox.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #include <CommInterface.au3> #include <GuiListBox.au3> #include <Date.au3> #include <SQLite.au3> #include <SQLite.dll.au3> #include <File.au3> #include <GuiRichEdit.au3> #Region ### START Koda GUI section ### Form=c:\users\jimbecher\desktop\idem v2.10\koda_1.7.2.0\forms\efdeck.kxf $EFDeck = GUICreate("EF Deck Display", 755, 248, 1001, 271) $EFDAvgTemp1 = _GUICtrlRichEdit_Create ($EFDeck,"", 184, 24, 57, 19) $EFDAvgTemp2 = _GUICtrlRichEdit_Create ($EFDeck,"", 184, 112, 57, 19) $EFDAvgTemp3 = _GUICtrlRichEdit_Create ($EFDeck,"", 184, 200, 57, 19) $EFDLimit1 = _GUICtrlRichEdit_Create ($EFDeck,"", 328, 24, 57, 19) $EFDLimit2 = _GUICtrlRichEdit_Create ($EFDeck,"", 328, 112, 57, 19) $EFDLimit3 = _GUICtrlRichEdit_Create ($EFDeck,"", 328, 200, 57, 19) $EFDExceeded1 = _GUICtrlRichEdit_Create ($EFDeck,"", 528, 24, 17, 19) $EFDExceeded2 = _GUICtrlRichEdit_Create ($EFDeck,"", 529, 112, 15, 19) $EFDExceeded3 = _GUICtrlRichEdit_Create ($EFDeck,"", 528, 200, 17, 19) $EFDReadings1 = _GUICtrlRichEdit_Create ($EFDeck,"", 672, 24, 57, 19) $EFDReadings2 = _GUICtrlRichEdit_Create ($EFDeck,"", 672, 112, 57, 19) $EFDReadings3 = _GUICtrlRichEdit_Create ($EFDeck,"", 672, 192, 57, 19) $Label2 = GUICtrlCreateLabel("Limit Exceeded:", 448, 24, 79, 17) $Label1 = GUICtrlCreateLabel(" 3 Hr Avg Temp:", 104, 24, 82, 17) $Label3 = GUICtrlCreateLabel("Readings:", 616, 24, 52, 17) $Label5 = GUICtrlCreateLabel("Baghouse 1", 32, 24, 61, 17) $Label9 = GUICtrlCreateLabel("3 Hr Avg Temp:", 104, 112, 79, 17) $Label10 = GUICtrlCreateLabel("Limit Exceeded:", 448, 112, 79, 17) $Label11 = GUICtrlCreateLabel("Readings:", 616, 112, 52, 17) $Label13 = GUICtrlCreateLabel("Baghouse 2", 32, 112, 61, 17) $Label17 = GUICtrlCreateLabel("3 Hr Avg Temp:", 104, 200, 79, 17) $Label18 = GUICtrlCreateLabel("Limit Exceeded:", 440, 200, 79, 17) $Label19 = GUICtrlCreateLabel("Readings:", 616, 192, 52, 17) $Label21 = GUICtrlCreateLabel("Baghouse 3", 32, 200, 61, 17) $Label37 = GUICtrlCreateLabel("Limit: ", 296, 24, 31, 17) $Label38 = GUICtrlCreateLabel("Limit:", 296, 112, 28, 17) $Label39 = GUICtrlCreateLabel("Limit", 296, 200, 25, 17) GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### ColorWrite($EFDLimit1, 1 & @CRLF, -6, "", 0x000000) ColorWrite($EFDLimit2, 2 & @CRLF, -6, "", 0x000000) ColorWrite($EFDLimit3, 3 & @CRLF, -6, "", 0x000000) While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE GUIDelete() Exit EndSwitch WEnd Func ColorWrite($hWnd, $sText, $iIncrement = 0, $sAttrib = "", $iColor = -1) ; Count the @CRLFs StringReplace(_GUICtrlRichEdit_GetText($hWnd, True), @CRLF, "") Local $iLines = @extended ; Adjust the text char count to account for the @CRLFs Local $iEndPoint = _GUICtrlRichEdit_GetTextLength($hWnd, True, True) - $iLines ; Add new text _GUICtrlRichEdit_AppendText($hWnd, $sText & @CRLF) ; Select text between old and new end points _GuiCtrlRichEdit_SetSel($hWnd, $iEndPoint, -1) ; Convert colour from RGB to BGR $iColor = Hex($iColor, 6) $iColor = '0x' & StringMid($iColor, 5, 2) & StringMid($iColor, 3, 2) & StringMid($iColor, 1, 2) ; Set colour If $iColor <> -1 Then _GuiCtrlRichEdit_SetCharColor($hWnd, $iColor) ; Set size If $iIncrement <> 0 Then _GUICtrlRichEdit_ChangeFontSize($hWnd, $iIncrement) ; Set weight If $sAttrib <> "" Then _GUICtrlRichEdit_SetCharAttributes($hWnd, $sAttrib) ; Clear selection _GUICtrlRichEdit_Deselect($hWnd) EndFunc >  
    • By kcvinu
      Hi all,
      I want to show a color dialog box to user from my script. Is it possible ? I searched in help file but can't find anything related to a color dialog. 
    • By Miliardsto
      hello Im wondering if it is possible to process image in autoit like this
      1. firstly there is colorfull wallpaper
      2. Fill all colors (exception rose color) - with white
      3. Fill rose color with black color
      I see Gdi functions have things to manipulate images
      https://imgur.com/a/lFdY26g
    • By Miliardsto
      Im wondering if its possible to read pixel colors from not only from top window.
      For example I got a few windows with images how (in attachment video) . Is it possible to read pixel color for example 200px, 200px from top left ?
      Can i make something like winlist for the same window names and then get handles for every listed exact name window and then read for every window pixel color for example: 200px, 200px from top left ?
      https://streamable.com/l3pit
       
      2018-12-10 01-02-38.mp4
    • By AndyS01
      I want to create a slider that has values representing colors, like the slider on the _ChooseColor() GUI in the Misc.au3 UDF, but the max value for a slider is 32767.  
      Here is my test code:
      #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <SliderConstants.au3> #include <Misc.au3> $hGUI = GUICreate("Test", 100, 560) $BtnID = GUICtrlCreateButton("Choose", 10, 10, 50, 25) ;~ GUICtrlSetOnEvent($BtnID, "handle_choose_btn") $flags = BitOR($TBS_AUTOTICKS, $TBS_VERT) $iSliderID = GUICtrlCreateSlider(10, 50, 40, 420, $flags) $hSlider_hWnd = GUICtrlGetHandle($iSliderID) $iMaxVal = 32767 GUICtrlSetLimit($iSliderID, $iMaxVal, 0) ; change min/max value GUISetState() GUIRegisterMsg($WM_VSCROLL, "WM_V_Slider") While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit Case $GUI_EVENT_PRIMARYUP ToolTip("") case $BtnID handle_choose_btn() EndSwitch WEnd ; React to a slider movement Func WM_V_Slider($hWnd, $iMsg, $wParam, $lParam) #forceref $hWnd, $iMsg, $wParam If $lParam = $hSlider_hWnd Then $iValue = GUICtrlRead($iSliderID) ConsoleWrite("+++: $iValue = " & $iValue & @CRLF) ToolTip(getRGB($iValue)) EndIf Return $GUI_RUNDEFMSG EndFunc ;==>WM_V_Slider ; Extract the RGB components from the color value Func getRGB($iColorVal) Local $hexstr, $b, $g, $r, $rgb $hexstr = StringFormat("%06X", $iColorVal) $r = StringMid($hexstr, 1, 2) $g = StringMid($hexstr, 3, 2) $b = StringMid($hexstr, 5, 2) $rgb = StringFormat("" & $iColorVal & " - rgb: %02s %02s %02s", $r, $g, $b) Return ($rgb) EndFunc ;==>getRGB Func handle_choose_btn() $color = _ChooseColor(2, 255, 0, $hGUI) ConsoleWrite("+++: $color = " & Hex($color, 8) & @CRLF) EndFunc ;==>handle_choose_btn  
×
×
  • Create New...