Home > front end >  Delphi DrawGrid.Canvas.TextRect changes & to _
Delphi DrawGrid.Canvas.TextRect changes & to _

Time:07-23

I have a TDrawGrid where I am using its OnDrawCell event, and in there the Canvas.TextRect() method is used to fill out the cells with strings. One of the strings contains an &, but it gets displayed as an underscore _.

I don't see anything wrong, there is nothing fancy with this grid, and elsewhere it seems to work fine. Also the debugger confirms that the string is correct when passing it to Canvas.TextRect().

What am I missing?

Delphi 11, 64-bit, Windows 11.

CodePudding user response:

This is expected. In Microsoft Windows, menu items, buttons, and control labels use an underscore to indicate the corresponding keyboard shortcut, and this underlined character is indicated using a prefix ampersand in code.

For instance, the &File menu item (displayed as File with F underlined) can be accessed by pressing Alt F. A &Save button (displayed as Save with S underlined) may be invoked by pressing Alt S (or only S if the currently focused control doesn't accept character input). You can set focus to a text field with label &Name: (displayed as Name: with N underlined) by pressing Alt N.

This is why a string like Lost & Found is displayed as Lost _Found in Windows.

If you don't want ampersands to be treated as accelerator character indicators, simply use the tfNoPrefix flag:

Canvas.TextRect(R, S, [tfNoPrefix])

This VCL flag corresponds to the Win32 API DT_NOPREFIX flag:

Turns off processing of prefix characters. Normally, DrawText interprets the mnemonic-prefix character & as a directive to underscore the character that follows, and the mnemonic-prefix characters && as a directive to print a single &. By specifying DT_NOPREFIX, this processing is turned off.

  • Related