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.
-
If you can use Delphi code for inspiration, enter `[delphi] Ctrl+P` in the search box. There are plenty of examples. For example: https://stackoverflow.com/q/33705163/2292722 – Tom Brunberg Nov 09 '20 at 08:09
2 Answers
Place a TActionList
or TActionManager
onto your Form, and then add the standard TPrintDlg
action to it. You can then set the action's ShortCut
property to Ctrl+P, and the VCL will invoke the action for you automatically when that keyboard shortcut is pressed:
TPrintDlg is the standard action for displaying a print dialog.
Add TPrintDlg to an action list to add a print dialog to your application. Controls such as menu items and tool buttons linked to this action cause the application to display the print dialog (TPrintDialog) when invoked. Write an OnAccept event handler to perform the actual printing when the user clicks OK. You can read details about the user's selections in the dialog from the Dialog property.
See Embarcadero's documentation for more details:

- 555,201
- 31
- 458
- 770
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:

- 49,595
- 11
- 110
- 380
-
1To use the `OnKey(Down|Up)` events at the Form level, you usually need to set the Form's `KeyPreview` property to true, otherwise keystrokes will be sent only to the focused control and not to the Form itself. – Remy Lebeau Nov 09 '20 at 21:14
-
Remy, making this addition was important and I didn't know about it. This addition helped to make the app's behavior more consistent. Thanks. – Bob Penoyer Nov 10 '20 at 00:30
-
-
@RemyLebeau good point (I knew about it just forgot to mention ...) just need to add that other key events must not change the `Key` parameter when `P` is pressed (its similar to `Handled`) – Spektre Nov 10 '20 at 06:14