KeyPress events and minimizing the application


#1

I am trying to create something like a quicklauncher that can be displayed on top of all other windows when a particular key combination is pressed and then minimized back into the system tray if that combination is pressed again.

My current code inside the keyPressed function is:



class ViewToggleKeyListener : public KeyListener{
public:
    bool keyPressed (const KeyPress &key, Component* originatingComponent);
};
    
bool ViewToggleKeyListener::keyPressed (const KeyPress &key, Component* originatingComponent){
    static KeyPress targetCombination('T', ModifierKeys::ctrlModifier, NULL);
    if(key == targetCombination){
        originatingComponent->setVisible(!originatingComponent->isVisible());
        originatingComponent->grabKeyboardFocus();
    }
    return false;
}

This works when the application is initially launched but the keyPressed function is not called again once the application is not visible anymore. 

Is there a way to have a 'global' keypress listener so that I can toggle this application between a state where it is on top of all other windows and minimized into the system tray? 

Thanks in advance!


#2

I think that for very sensible security reasons, OSes don't let non-focused apps intercept keypresses that were sent to other windows!


#3

There are probably ways to set up mouse and keyboard hooks on Windows.

http://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C


#4

Ah yes, never thought about how I was creating an inadvertant keylogger!

I looked into the windows functions and found a function called RegisterHotKey that allows for functionality like this. I tried implementing it like so inside the MainWindow() constructor in main.cpp:

Component* MainComponentPointer = new MainContentComponent();
MainComponentPointer->setComponentID("MainContentComponent");
setContentOwned (MainComponentPointer, true);

HWND hwnd = static_cast<HWND>(MainComponentPointer->getWindowHandle());
// Handle matching alt+b
RegisterHotKey(hwnd, 0, MOD_ALT | MOD_NOREPEAT, 0x42);
MSG msg = {0};
while(GetMessage(&msg, hwnd, 0, 0) != 0){
    if(msg.message == WM_HOTKEY){
        MainComponentPointer->setVisible(!MainComponentPointer->isVisible());
    }
}

My main.cpp is generated by introjucer and MainComponentPointer is a pointer to the component that I want toggled in and out. This however just seems to hang the application and nothing launches.

I set some breakpoints within the while loop, the loop gets triggerred when I press the hotkey and the setVisible() method is reached, but the component does not trigger and the application exits the while loop again, just to be re triggerred when I press the hot key. 

Am I placing this code in the wrong place or is the code itself wrong? I'm not sure how to integrate the bare windows functions with JUCE here and any help would be appreciated!