Snippets ( AutoIt Mouse & Keyboard )

From AutoIt Wiki
Jump to navigation Jump to search

Please always credit an author in your script if you use their code. It is only polite.


Control Button by HotKey

Author: SmOke_N







http://www.autoitscript.com/forum/index.php?s=&showtopic=36564&view=findpost&p=270412


; Control Button by HotKey
; http://www.autoitscript.com/forum/index.php?s=&showtopic=36564&view=findpost&p=270412
HotKeySet("+4", "_ClickButton")

Global Const $Main = GUICreate("Some GUI", 200, 100)

Global Const $Button = GUICtrlCreateButton("Some Button To Click", 10, 35, 180, 30)

Global $fClickit

GUISetState(@SW_SHOWNORMAL)

While 1
    Switch GUIGetMsg()
        Case - 3
            Exit
        Case $Button
            If Not $fClickit Then
                MsgBox(64, "Clicked", "You clicked the button")
            Else
                $fClickit = Not $fClickit
                MsgBox(64, "Clicked", "You used a hotkey to click the button")
            EndIf
    EndSwitch
WEnd

Func _ClickButton()
    $fClickit = Not $fClickit
    ControlClick(HWnd($Main), '', $Button)
EndFunc

ReturnToContents

_ControlMouseClick

Author: fett8802








; #FUNCTION# ====================================================================================================================
; Name...........: _ControlMouseClick
; Description ...: Use the mouse to move to a control and click it
; Syntax.........: _ControlMouseClick($iTitle, $iText, $iControl [, $iButton = "left" [, $iClicks = "1" [, $iSpeed = "10" [, $iXpos = '' [, $iYpos = '' ]]]]] )
; Parameters ....: $iTitle  - The title of the window containing the control
;      $iText  - Some text from the window containing the control. Can enter no text be using ''
;      $iControl - The Control ID of the control to click
;      $iButton  - [optional] The button to click: "left", "right", "middle", "main", "menu", "primary", "secondary". Default is "left"
;      $iClicks  - [optional] The number of times to click the mouse. Default is 1.
;      $iSpeed  - [optional] The speed to move the mouse in the range 1 (fastest) to 100 (slowest). A speed of 0 will move the mouse instantly. Default speed is 10.
;      $iXpos  - [optional] The x position to click within the control. Default is center.
;      $iYpos  - [optional] The y position to click within the control. Default is center.
; Author ........: Kris Mills <fett8802 at gmail dot com>
; UserCallTip....: _ControlMouseClick ( "title", "text", controlID [, button [, clicks [, speed [, x [, y ]]]]] ) Use the mouse to move to a control and click it.(required: #include <KrisUDF.au3>)
; ===============================================================================================================================
Func _ControlMouseClick($iTitle, $iText, $iControl, $iButton = "left", $iClicks = "1", $iSpeed = "10", $iXpos = '', $iYpos = '')
	$iOriginal = Opt("MouseCoordMode", 2) ;Change the MouseCoordMode to relative coords and get the previous setting
	$aPos = ControlGetPos($iTitle, $iText, $iControl) ;Get the position of the given control
	MouseClick($iButton, $aPos[0] + ($aPos[2] / 2) + $iXpos, $aPos[1] + ($aPos[3] / 2) + $iYpos, $iClicks, $iSpeed) ;Move the mouse and click on the given control
	Opt("MouseCoordMode", $iOriginal) ;Change the MouseCoordMode back to the original
EndFunc   ;==>_ControlMouseClick

ReturnToContents

Get Mouse Position

Author: shmuelw1








; This script returns the current mouse position
; Edit the value of $mode as required
#include <Misc.au3> ; required for _IsPressed

Global $mode = 0 ; this sets the MouseCoordMode - see Opt("MouseCoordMode" later in the script
Global $modeText
Global $pos

Opt("MouseCoordMode", $mode) ; 1 = absolute screen position, 0 = relative to active windows, 2 = relative to client area
Opt("TrayIconDebug", 1)

Switch $mode
    Case 0
        $modeText = "relative to the active window is:" & @CRLF
    Case 1
        $modeText = "from the top-right of the screen is:" & @CRLF
    Case 2
        $modeText = "relative to the client area of the active window is:" & @CRLF
EndSwitch

ToolTip("Move the pointer to the desired location. Press Enter to continue.", @DesktopWidth/2-250, @DesktopHeight/2-10)

While Not _IsPressed("0D") ; wait for Enter key
    Sleep(100)
WEnd

ToolTip('') ; close ToolTip

$pos = MouseGetPos()

MsgBox(0, "Mouse Position", "The mouse position " & $modeText & $pos[0] & "," & $pos[1] & " (x,y)")

ReturnToContents

Get Mouse Position With Hotkey

Author: shmuelw1







This script returns the current mouse position


; 2013/08/24 20:58 PM -> Code tidied by DatMCEyeBall

; This script returns the current mouse position
; Edit the value of $mode as required

#include <Misc.au3> ; required for _IsPressed

Global $mode = 0 ; this sets the MouseCoordMode - see Opt("MouseCoordMode" later in the script
Global $modeText
Global $pos

Opt("MouseCoordMode", $mode) ;1=absolute screen position, 0=relative to active windows, 2= relative to client area
Opt("TrayIconDebug", 1)

HotKeySet("^#s", "_GetPosition") ; ! = ALT keystroke, + = SHIFT, ^ = CONTROL, # = Windows key

Switch $mode
	Case 0
		$modeText = "relative to the active window is:" & @CRLF
	Case 1
		$modeText = "from the top-right of the screen is:" & @CRLF
	Case 2
		$modeText = "relative to the client area of the active window is:" & @CRLF
EndSwitch

While 1
	Sleep(100)
WEnd

Func _GetPosition()
	ToolTip("Move the pointer to the desired location. Press Enter to continue.", @DesktopWidth / 2 - 250, @DesktopHeight / 2 - 10)

	While Not _IsPressed("0D") ; wait for Enter key
		Sleep(100)
	WEnd

	ToolTip('') ; close ToolTip

	$pos = MouseGetPos()

	MsgBox(0, "Mouse Position", "The mouse position " & $modeText & $pos[0] & "," & $pos[1] & " (x,y)")
EndFunc   ;==>_GetPosition

ReturnToContents

_IsLeftHandedMouse

Author: guinness








#include <WinAPI.au3>
#include <WindowsConstants.au3>

ConsoleWrite( _IsLeftHandedMouse() & @CRLF)

Func _IsLeftHandedMouse()
    Return _WinAPI_GetSystemMetrics($SM_SWAPBUTTON) > 0
EndFunc   ;==>_IsLeftHandedMouse

ReturnToContents

_IsRightHandedMouse

Author: guinness








#include <WinAPI.au3>
#include <WindowsConstants.au3>

#include <WinAPI.au3>
#include <WindowsConstants.au3>

MsgBox(64, "_IsRightHandedMouse()", _IsRightHandedMouse())

Func _IsRightHandedMouse()
    Return _WinAPI_GetSystemMetrics($SM_SWAPBUTTON) = 0
EndFunc   ;==>_IsRightHandedMouse

ReturnToContents

Is Mouse Over GUI

Author: MrCreatoR




Modified: Valuater




Check if Mouse is over a GUI


; Check if Mouse is over a GUI

#include <GUIConstants.au3>

Global $ParentWin = GUICreate("GetHoveredHwnd")

GUISetState(@SW_SHOWNORMAL)

While 1
    If GUIGetMsg() = -3 Then Exit

    If GetHoveredHwnd() = $ParentWin Then
        ToolTip("You are over the GUI")
    Else
        ToolTip('')
    EndIf
WEnd

Func GetHoveredHwnd()
    Local $iRet = DllCall("user32.dll", "int", "WindowFromPoint", "long", MouseGetPos(0), "long", MouseGetPos(1))
    If IsArray($iRet) Then Return HWnd($iRet[0])
    Return SetError(1, 0, 0)
EndFunc

ReturnToContents

_IsMouseInstalled

Author: guinness








#include <WinAPI.au3>
#include <WindowsConstants.au3>

MsgBox(64, "_IsMouseInstalled()", _IsMouseInstalled())

Func _IsMouseInstalled()
    Return _WinAPI_GetSystemMetrics($SM_CMOUSEBUTTONS) > 0
EndFunc   ;==>_IsMouseInstalled

ReturnToContents

_IsMouseWheelPresent

Author: guinness








#include <WinAPI.au3>
#include <WindowsConstants.au3>

ConsoleWrite(_IsMouseWheelPresent() & @CRLF)

Func _IsMouseWheelPresent()
    Return _WinAPI_GetSystemMetrics($SM_MOUSEWHEELPRESENT) > 0
EndFunc   ;==>_IsMouseWheelPresent

ReturnToContents

_MouseRepel

Author: The Kandie Man




Modified: DatMCEyeBall




Mouse repel - keep mouse away from an area


; GUI snap to corners
; Mouse repel - keep mouse away from an area
; Author - The Kandie Man
; 2013/08/24 21:11 PM -> Modified for GUI, left in the AdlibRegister for non-GUI uses -> DatMCEyeBall.

#include <WindowsConstants.au3> ;For the $WM_NOTIFY const.

Global Const $GUI = GUICreate("Can't Touch This", 200, 100, 200, 200)

GUISetState(@SW_SHOWNORMAL)

; AdlibRegister("CallMouseRepel", 10) ; Use for non-GUI purposes.
GUIRegisterMsg($WM_MOUSEMOVE, "CallMouseRepel") ;Cleaner way of doing it for a GUI.

While 1
    $nMsg = GUIGetMsg()
    If $nMsg = -3 Then Exit
WEnd

Func CallMouseRepel()
    Local Const $coords = WinGetPos($GUI)
    _MouseRepel($coords[0], $coords[1], $coords[0] + $coords[2], $coords[1] + $coords[3])
EndFunc   ;==>CallMouseRepel

;===============================================================================
; Description:    _MouseRepel
; Parameter(s):   $i_left - Left coord
;                 $i_top - Top coord
;                 $i_right - Right coord
;                 $i_bottom - Bottom coord
; User CallTip:   _MouseRepel([$i_left = 0[, $i_top = 0[, $i_right = 0[, $i_bottom = 0]]]]) Repel the Mouse Cursor to specified coords.
; Author(s):      The Kandie Man
; Note(s):        This function must be called constantly to prevent the mouse cursor from entering the area.
;                 It is therefore recommended that you call this function from another function that is called by AdlibEnable every 1 to 50ms.
;===============================================================================
Func _MouseRepel($i_left = 0, $i_top = 0, $i_right = 0, $i_bottom = 0)
    Local $a_MousePos = MouseGetPos()

    Local $i_XCordinate = -1, $i_YCordinate = -1

    If $a_MousePos[0] >= $i_left And $a_MousePos[0] <= $i_right Then
        If ($a_MousePos[0] - $i_left) < ($i_right - $a_MousePos[0]) Then
            $i_XCordinate = $i_left - 1
        Else
            $i_XCordinate = $i_right + 1
        EndIf
    EndIf

    If $a_MousePos[1] >= $i_top And $a_MousePos[1] <= $i_bottom Then
        If ($a_MousePos[1] - $i_top) < ($i_bottom - $a_MousePos[1]) Then
            $i_YCordinate = $i_top - 1
        Else
            $i_YCordinate = $i_bottom + 1
        EndIf
    EndIf

    If $i_XCordinate <> -1 And $i_YCordinate <> -1 Then
        If Abs($i_XCordinate - $a_MousePos[0]) > Abs($i_YCordinate - $a_MousePos[1]) Then
            MouseMove($a_MousePos[0], $i_YCordinate, 1)
        ElseIf Abs($i_XCordinate - $a_MousePos[0]) < Abs($i_YCordinate - $a_MousePos[1]) Then
            MouseMove($i_XCordinate, $a_MousePos[1], 1)
        Else
            MouseMove($i_XCordinate, $i_YCordinate, 1)
        EndIf
    EndIf
EndFunc   ;==>_MouseRepel

ReturnToContents

_MyMouseMove

Author: martin








; Work with any screen resolution
; This is for the 1440 x 900 screen - change as needed

Global Const $iHeight = 900
Global Const $iWidth = 1440

_MyMouseMove(100, 200)

Func _MyMouseMove($iX, $iY)
	Return MouseMove(@DesktopWidth * $iX / $iWidth, @DesktopHeight * $iY / $iHeight)
EndFunc   ;==>_MyMouseMove

ReturnToContents

Restricted Input Keys - All USB Devices

Multiple Authors








#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

Global $iInput = 99

; Restricted keys in an input "[\/:*?"<>\|]"

Example()

Func Example()
	Local Const $hGUI = GUICreate("Input Filter", 300, 30, -1, -1)

	$iInput = GUICtrlCreateInput('', 5, 5, 290)

	GUIRegisterMsg($WM_COMMAND, "WM_COMMAND")

	GUISetState(@SW_SHOWNORMAL, $hGUI)

	While 1
		Switch GUIGetMsg()
			Case $GUI_EVENT_CLOSE
				ExitLoop
		EndSwitch
	WEnd

	GUIDelete($hGUI)
EndFunc   ;==>Example


Func WM_COMMAND($hWnd, $iMsg, $wParam, $lParam)
	#forceref $hWnd, $iMsg, $wParam, $lParam
	Return GUICtrlSetData($iInput, StringRegExpReplace(GUICtrlRead($iInput), '[\\/ :* ?"<>\|]', ''))
EndFunc   ;==>WM_COMMAND

ReturnToContents

Two Tray Mouse Menus

Author: smashly








; Two Tray Menus - Right & Left Click On Icon

#include <Constants.au3>

Opt("TrayOnEventMode",1)
Opt("TrayMenuMode",1)

TraySetClick(18)

Global $Tray[11], $state = 2

TrayCreateItem('')
TrayCreateItem("Exit")
TrayItemSetOnEvent(-1, "TrayEvent")
TraySetOnEvent($TRAY_EVENT_PRIMARYDOWN, "TrayMenuLeftClick")
TraySetOnEvent($TRAY_EVENT_SECONDARYDOWN, "TrayMenuRightClick")
TraySetState()

While 1
    Sleep(100)
WEnd

Func TrayMenuLeftClick()
    If $state = 0 Or $state = 2 Then
        $state = 1
        For $i = 6 to 10
            TrayItemDelete($Tray[$i])
        Next
        For $i = 1 to 5
            $Tray[$i] = TrayCreateItem("1st Menu Item - " & $i, -1, $i -1 )
            TrayItemSetOnEvent(-1, "TrayEvent")
        Next
    EndIf
EndFunc

Func TrayMenuRightClick()
    If $state = 1 Or $state = 2 Then
        $state = 0
        For $i = 1 to 5
            TrayItemDelete($Tray[$i])
        Next
        For $i = 6 to 10
            $Tray[$i] = TrayCreateItem("2nd Menu Item - " & $i - 5, -1, $i - 6)
            TrayItemSetOnEvent(-1, "TrayEvent")
        Next
    EndIf
EndFunc

Func TrayEvent()
    MsgBox(0, '', TrayItemGetText(@TRAY_ID))
    If TrayItemGetText(@TRAY_ID) = "Exit" Then Exit
EndFunc

ReturnToContents

_WinAPI_SwapMouseButton

Author: guinness








Example()

Func Example()
    ; Swap the left button to generate right-button messages and vice versa.
    ConsoleWrite(_WinAPI_SwapMouseButton(True) & @CRLF)

    ; Wait for the user to see the changes.
    Sleep(10000)

    ; Change the mouse buttons back to their original meanings.
    ConsoleWrite(_WinAPI_SwapMouseButton(False) & @CRLF)
EndFunc   ;==>Example

; If $fFlag is True, the left button generates right-button messages and the right button generates left-button messages.
; If $fFlag is False, the buttons are restored to their original meanings.
Func _WinAPI_SwapMouseButton($fFlag)
    Local $aReturn = DllCall('user32.dll', 'int', 'SwapMouseButton', 'int', $fFlag)
    If @error Then
        Return SetError(1, 0, 0)
    EndIf
    Return $aReturn[0]
EndFunc   ;==>_WinAPI_SwapMouseButton

ReturnToContents