Search code examples
keycombinationsc++builder

How to detect the Ctrl+P key combination in Embarcadero C++Builder


I'm using C++Builder 10.4.1. I want to use the Ctrl+P combination to open the PrintDialog but I don't know how to detect the Ctrl+P key combination.


Solution

  • Use OnKeyDown event it returns 16 bit extended key code (so you got also num pad arrows and other stuff)...

    void __fastcall TForm1::FormKeyDown(TObject *Sender, WORD &Key, TShiftState Shift)
        {
    //  Caption=Key; // this will print aktually pressed key code to caption
        if ((Key=='P')&&(Shift.Contains(ssCtrl)))
            Caption="print"; // here open your dialog
        }
    

    so for keys test the Key value and for special keys and buttons test Shift (you know shift,ctrl,alt,mouse buttons)

    There is also:

    void __fastcall TForm1::FormShortCut(TWMKey &Msg, bool &Handled)
        {
        static bool ctrl=false;
        if (Msg.CharCode=='P')
            {
            Caption="print2";
            Handled=true;
            }
        ctrl=(Msg.CharCode==VK_LCONTROL)||(Msg.CharCode==VK_RCONTROL);
        }
    

    Which has major priority over other key/mouse events. However it can only recognize the TWMKey codes which I do not like and for unsuported key combinations you need to do a hack like I did in example above...

    In case you want more combinations or keep track of which keys are pressed (movement controls...) then you have to implement a key map table something like this: