Jump to content

Keyboard Pressed / Filter


Recommended Posts

I'm currently stuck at a simple (obviously not for me simple...) problem.

problem:

I want to check if a user is availabe on system start, to check this condition a gui is shown and waits for a given time for a certain key to be pressed, eg. the NUMPAD 3 key.

If NUMPAD3 is pressed than the app exist with exit(0) , in case of time-out it exists with (1) and if a different keyboard input is processed it should exit with exit(2).

No mouse is given, so only keyboard is available (for other reasons)

So if I use hotkey, the program will only be triggered on this one key but not on others.

If I use _ispressed than the else condition is always true, because _ispressed returns "0" if no key is pressed or a other key is pressed (correct?)

Question:

Is there a simpler way to get other key pressed than including a bunch of ifelse/switch code block?

Code extract that shows my issue.

I hope that someone could tell me if there is something like

If _IsPressed("63", $dll) Then
        consolewrite("NumPad3 Key Pressed")
   elseif
        consolewrite("other Key Pressed")
   else
         consolewrite("no Key Pressed")
    EndIf

#NoTrayIcon

#region AutoIt3Wrapper
#AutoIt3Wrapper_UseX64=N                         ;(Y/N) Use X64 versions for AutoIt3_x64 or AUT2EXE_x64. Default=N
#AutoIt3Wrapper_Version=P                       ;(B/P) Use Beta or Production for AutoIt3 and AUT2EXE. Default is P
#AutoIt3Wrapper_Run_Debug_Mode=              ;(Y/N)Run Script with console debugging. Default=N
#AutoIt3Wrapper_Run_SciTE_Minimized=            ;(Y/N) Minimize SciTE while script is running.
#AutoIt3Wrapper_Run_SciTE_OutputPane_Minimized= ;(Y/N) Toggle SciTE output pane at run time so its not shown by default.
#AutoIt3Wrapper_Change2CUI=Y                     ;(Y/N) Change output program to CUI in stead of GUI. Default=N
#AutoIt3Wrapper_Res_Fileversion=1.0.0.1
#AutoIt3Wrapper_Res_FileVersion_AutoIncrement=P  ;(Y/N/P)AutoIncrement FileVersion After Aut2EXE is finished. default=N
#EndRegion

#region Include
#Include <Array.au3>
#include <Constants.au3>
#Include <Date.au3>
#include <Debug.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>

#include <Misc.au3>
#Region include end

#Region Define Vars
Global $X_width,$Y_Height,$Key_Check,$TimeOut
global $Form1,$Label1,$Label2,$Label3

#EndRegion Define vars


$dll = DllOpen("user32.dll")
ConsoleWrite(@CRLF)

local $Debug_Flg=true

if $Debug_Flg==True Then
    $X_width=500
    $Y_Height=200
    $Key_Check=63
    $TimeOut=10
     $LogFile=@SCRIPTDIR&""&@ScriptName&".LOG"
Else
;~   getCommandline()
EndIf

_DebugSetup("PC_BEEP",False,2,$LogFile)

_DebugOut("$X_width="&$X_width)
_DebugOut("$Y_Height="&$Y_Height)
_DebugOut("$Key_Check="&$Key_Check)
_DebugOut("$TimeOut="&$TimeOut)

_DebugOut("$LogFile="&$LogFile)

CheckKey($X_width,$Y_Height,$Key_Check,$TimeOut)

_DebugOut("...finished")
ConsoleWrite(@CRLF&"...finished"&@CRLF)
Exit

func CreateGui()

$Form1 = GUICreate("keyboard Checker", 625, 443, 0, 0)
$Label1 = GUICtrlCreateLabel("Press now the Numpad3 key", 11, 72, 602, 41)
GUICtrlSetFont(-1, 24, 400, 0, "MS Sans Serif")
$Label2 = GUICtrlCreateLabel("timeout before exit:", 26, 183, 573, 41)
GUICtrlSetFont(-1, 24, 400, 0, "MS Sans Serif")
$Label3 = GUICtrlCreateLabel("00", 230, 267, 165,90, $SS_Center, "")
GUICtrlSetFont(-1, 72, 400, 0, "ARIAL")
GUISetState(@SW_SHOW)

    EndFunc
func KEY_OK()
    ConsoleWrite(@CRLF&"Correct Key "&$Key_Check&"pressed."&@CRLF)
    GUICtrlSetData($Label3,"OK")
    GUICtrlSetColor($Label3, 0x00a000)
    sleep(2000)
    Exit(0)
EndFunc

func Key_NOTOK()
    GUICtrlSetData($Label3,"NOT OK")
    GUICtrlSetFont($Label3, 24, 400, 0, "ARIAL")
    GUICtrlSetColor($Label3, 0xaa0000)
    sleep(2000)
    DllClose($dll)
    exit(1)
    EndFunc

Func CheckKey($X_width,$Y_Height,$Key_Check,$TimeOut)
    $BeginTimer=TimerInit()
    CreateGui()

    While 1
    $CurrentTimer=Round((TimerDiff($BeginTimer)/1000),0)
    $DiffTimer=$Timeout-$CurrentTimer

    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            DllClose($dll)
            Exit
    EndSwitch
    If _IsPressed($Key_Check, $dll) Then
        KEY_OK()

    EndIf


    if (GUICtrlRead($Label3)<>$DiffTimer) Then
        GUICtrlSetData($Label3,$DiffTimer)
    EndIf
    sleep(100)
    $DiffTimer=$Timeout-$CurrentTimer
    if $DiffTimer<=0 Then
        Key_NOTOK()
    EndIf

    WEnd

    EndFunc

I hope the answer is not: "Look here and use search you #!+!!###!, already answered 324.564 times before...."

But I used search even in the German version of this forum, without luck or the correct words to search for....

Edited by Tankbuster
Link to comment
Share on other sites

  • Moderators

Tankbuster,

What you want to do can be done very easily in AutoIt - but the code to check which key was pressed is essentially a keylogger, which is one of the big no-go areas here. :)

If you are testing for the presence of a user, why do you need to check for any key other than the "special" one? Are you just looking for a "Yes/No" response from the user as to what should happen next? If so, why not use a GUI with accelerator keys associated with the controls:

#include <GUIConstantsEx.au3>

$hGUI = GUICreate("Test", 500, 500)

$cButton_Y = GUICtrlCreateButton("&Yes", 10, 10, 80, 30)
$cButton_N = GUICtrlCreateButton("&No", 100, 10, 80, 30)

GUICtrlCreateLabel("Press either 'Y' or 'N' - with or without Alt", 10, 100, 200, 20)

GUISetState()

; Set GUIAccelerators for the button controlIDs - y and n
Local $aAccelKeys[2][2] = [["y", $cButton_Y],["n", $cButton_N]]
GUISetAccelerators($aAccelKeys)

$iBegin = TimerInit()

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $cButton_Y
            MsgBox(0, "Pressed", "Yes")
            ExitLoop
        Case $cButton_N
            MsgBox(0, "Pressed", "No")
            ExitLoop
    EndSwitch

    If TimerDiff($iBegin) > 30 * 1000 Then
        MsgBox(0, "Time", "Out")
        ExitLoop
    EndIf
WEnd

Will that do? ;)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

_OptParse.au3 where to download?

Sorry my fault not needed for the dummy, remark it. I updated the script .

@Melba23

Yes, I know that it may look like a keylogger, but I'm only interessed in the keys sent to the app not systemwide (like a keylogger).

(...and to add also, I read the keylogger section in the example forum)

Anyway, for a very special reason I only got at that time numeric keypad (no it's not an ATM, just if someone asks...)

Let me explain the background:

On a touchscreen (3m touchware) there is a dll running converting touch areas to keystrokes (please do not ask why....), a certain area is defined as calculator like numerpad. touching a certain area gives NUMPAD1, NUMPAD2 and so on. But the rest of the screen is like a no-click area (for other reasons...)

BTW: to many "..." in this posting :-)

For an unknown reason the touch driver/controller looses sometimes the calibration (fullmoon, aliens, radiation....name the reason), so on system start I want to display the GUI and ask the user to press the NUMPAD3 area. in case a different key is found i want to start the calibration tool. And on time out I guess no one is able to calibrate and continue just as it would been successful . But logging that no touched the screen.

So your suggestion would work for me if the shutcut of a key could be set to NUMPAD3 (in my example), is this possible (nothing found in the help file)?

I remember a posting way back, that asks for a filter on keyboard.

Actually that was a keylogger (from a bahavior point of view) that uses a hook to catch all keyboard, examines if the needed key is found and otherwise parses the keys to the the system.

As far as I remember the person wanted to prevent the user to press a certain key. (window key?)

I agree with you , that if you think this is a keylogger discussion you should close this one, I will than ask for a bot....muhahaha :);)

Edited by Tankbuster
Link to comment
Share on other sites

Is it feasible to do something like this?

Set a HotKey for each numpad key (0-9?), where each HotKeySet calls the same function.

In that function, use Switch @HotKeyPressed, with each case executing code that needs to be run in that instance.

Here's an example of what I'm talking about:

HotKeySet('{F2}', "VolUpDownMute") ;ToggleMute
HotKeySet('{F3}', "VolUpDownMute") ;VolDown
HotKeySet('{F4}', "VolUpDownMute") ;VolUp

;;;

Func VolUpDownMute()
    Switch @HotKeyPressed
        Case '{F2}'
            Send("{VOLUME_MUTE}")
        Case '{F3}'
            Send("{VOLUME_DOWN}")
        Case '{F4}'
            Send("{VOLUME_UP}")
    EndSwitch
EndFunc

Now, I'm using function keys here (F2, F3, F4), but you should get the idea. I hope this helps.

Edited by somdcomputerguy

- Bruce /*somdcomputerguy */  If you change the way you look at things, the things you look at change.

Link to comment
Share on other sites

I used the keyboard layout posted by deltarocked to test the keys, there are still a few buttons to finish.

<snip>

Edited by Melba23
Keylogger code removed
Link to comment
Share on other sites

@Belini & SomeComputerGuy:

More or less that was the idea before I asked. But I thought there must be something simpler than defining all keys in a hotkey something. It does not look very smart ... ;)

But thank you for the link, I will use the Belini post as a starting point, because at least the keys are already inside. Thank you.

Maybe someday the _ispressed will offer something like this:

@error 2 = pressed but not this key

@error 1 = pressed key

@error 0 = no key is pressed

Anyway, thank you for trying to get a "optimised" solution.

Link to comment
Share on other sites

I found a for me better solution. As written before I thought that there is a post about keyboard hooks. And guess what it's already in the help file.....(ah sometimes it IS simple)

So now I use a modified script of

http://www.autoitscript.com/autoit3/docs/libfunctions/_WinAPI_SetWindowsHookEx.htm

to get my key.

Link to comment
Share on other sites

  • Moderators

TankBuster,

Here is another way to do what you want:

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

$hGui = GUICreate("Press any key...", 400, 100)

$cKey_Pressed = GUICtrlCreateDummy()

GUISetState()

GUIRegisterMsg($WM_KEYDOWN, "_KeyPressed")

$iBegin = TimerInit()

Do
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $cKey_Pressed
            If _IsPressed("63") Then
                MsgBox(0, "Key Pressed", "NumPad3")
            Else
                MsgBox(0, "Key Pressed", "Another key")
            EndIf
    EndSwitch

Until TimerDiff($iBegin) > 10* 1000

MsgBox(0, "Key Pressed", "No key pressed")

Func _KeyPressed()
    GUICtrlSendToDummy($cKey_Pressed)
EndFunc

A bit late but I got there in the end. ;)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Melba23,

thank you for the suggestion.

If a solution is that simple, it is obvious a clever one (see Columbus's egg) :)

I like your idea with the dummy control and the timer.

My current solution also works, but your suggestion looks much smaller and even I'm able to understand it with asking the forum ;)

I will replace the function with your code in my next version.

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...