3
votes

I use TMemo to be able to display multiple lines.

I want to change selected text attribute in TMemo into bold using the shortcut Ctrl+B.

For example, User enters "Hello, how are you?" in the Tmemo, I want when when user selects "How" and press Ctrl+B then only "How" should be appeared in Bold in that TMemo.

I use Delphi 7.

Please advice to get solution. thanks for help.

2
TMemo doesn't support that out of the box and it would require a lot of work to get it to do so. You may be better off switching to a TRichEdit and learn how to work with its formatting.Marjan Venema
Can't get TMemo to do it at all. Trivial with TRichEdit.David Heffernan
Any hint to make it possible using TRichEdit? thanksNalu
I am able to set font as Bold using RichEdit. Can someone help me to set the hotkey Ctrl+B to call xyz procedure.Nalu
@DavidHeffernan: You are probably right. I kept the possibility open because the TMS component suite has highlighting available in its memo components, and I didn't know their ancestry off the top of my head. Checked it. They are descending straight from TCustomControl...Marjan Venema

2 Answers

3
votes

You can't format text in a memo control. You need a rich edit control, TRichEdit.

In order to make the current selection bold you do this:

RichEdit.SelAttributes.Style := RichEdit.SelAttributes.Style + [fsBold];

The preferred way to invoke code in response to a shortcut like CTRL+A is to use actions. Add a TActionList to the form and add an action to that action list. Set the action's OnExecute event handler to point at code that performs the bolding of the selected text. Set the Shortcut property to Ctrl+A. Use actions so that you can centralise the control of user events. Typically there may also be a tool button, a menu item and a context menu item that performed the same action and this is where actions come into their own.

2
votes

Here's part of a program which I wrote which uses a RichEdit; part of the line is displayed in black, part in blue and possibly part in bold red. 'Text' is a field of the RichEdit.

procedure TWhatever.InsertText (const atext, btext, ctext: string);
begin
 with RichEdit1 do
  begin
   selstart:= length (text);
   sellength:= 0;
   SelAttributes.Color:= clBlack; 
   seltext:= '[' + atext + '] ';

   selstart:= length (text);
   sellength:= 0;
   SelAttributes.Color:= clBlue;
   seltext:= btext + ' ';

   if ctext <> '' then
    begin   // trap non-existent answers
     selstart:= length (text);
     sellength:= 0;
     SelAttributes.Color:= clRed;
     SelAttributes.Style:= [fsBold];
     seltext:= ctext + ' ';
     SelAttributes.Style:= [];
    end;
   lines.add ('');  // new line
  end;
end;