GetAsyncKeyState triggering when amibroker is not in focus

I'm using GetAsyncKeyState to detect key presses, however this is still happening when i'm not focused on amibroker ( eg, as I'm typing this question out, it's affecting how the script runs ).

Couple of options that I can think of:

  1. Can I check whether the script I want is in focus?

  2. Should I only use GetAsyncKeyState for Ctrl/Shift/Alt keys?

  3. Any other ways?


Hello mordrax,

you could combine GetAsyncKeyState and GetCursorXPosition to ensure your "keys pressed" only react if your "AB Chart Window" is in mouse focus.

Best regards,

1 Like

I think the intention is good, but it actually works out not to be great in practice.

I alt + tab between code and amibroker so if I put the mouse in the amibroker window, it will trigger keyboard events regardless of which window is active.
If I have the mouse outside of amibroker, it won't activate.

Without the mouse cursor check, it only intermittently picks up typing outside of amibroker. Amibroker doens't seem to pick up fast typing all the time... I'm now thinking of having a keyboard toggle to listen to keypress.

Here's what I tried to use with your suggestion:

function kb_events() {
    cursor = GetCursorXPosition(enumCursorPositionModeDateTimePrice);
    isFocused = Nz(cursor) != 0; 
    log_info(StrFormat("cursor: %f, isFocused: %f", cursor, isFocused));

    shift = kb_key(vk_Shift);

    key_l = kb_key(vk_l);
    key_n = kb_key(vk_N);
    key_p = kb_key(vk_P);

    if ( shift && key_p && isFocused) {
        Say("Back 10 trades");
    } else if ( key_n && isFocused) {
        Say("Next trade");

GetAsyncKeyState does NOT trigger anything. It your formula refreshing normally (because of real-time data arriving and/or RequestTimedRefresh calls).

Again: GetAsyncKeyState does NOT trigger execution of your formula.

All what GetAsyncKeyState does is to retrieve current keyboard state, REGARDLESS of what window is in focus. This function is transparent call to Windows API and it's function documented in Windows API docs

If you want to respond to key presses when given window has a focus and have your formula executed when user presses key INSIDE your window, you have to use Gui functions, namely GuiSendKeyEvents(), for example code see (as always) the great manual that covers everything you need to know about AmiBroker:

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.